无法从R数据框中删除空的“character(0)”或“list()”值

4nkexdtk  于 2022-12-25  发布在  其他
关注(0)|答案(2)|浏览(142)

我有一个R Dataframe ,单元格中有character(0)list()值。我想用NA值替换它们。
在以下示例中,字段"teaser"存在此问题,但它可以位于数据框中的任何位置。

df <- structure(list(body = "BAKER TO VEGAS 2022The Office fielded two squads this year in the 36th Annual Baker to Vegas (“B2V”) Challenge Cup Relay on April 9-10.  Members of our 2022 B2V Team include many staff and AUSAs who were joined by office alums and a cadre of friends and family who helped out during some rather brutal conditions this year with temperatures around 100 degrees for much of the days. Most importantly, everyone had fun… and nobody got hurt!  It was a great opportunity to meet (and run past) various members of our law enforcement community and to see the amazing logistics of the yearly event. Congratulations to all the participants.", 
    changed = structure(19156, class = "Date"), created = structure(19156, class = "Date"), 
    date = structure(19090, class = "Date"), teaser = "character(0)", 
    title = "Baker to Vegas 2022", url = "https://www.justice.gov/usao-cdca/blog/baker-vegas-2022", 
    uuid = "cd7e1023-c3ed-4234-b8af-56d342493810", vuuid = "8971702d-6f96-4bbd-ba8c-418f9d32a486", 
    name = "USAO - California, Central,"), row.names = 33L, class = "data.frame")

我试过很多方法都不管用,包括以下方法:

df <- na_if(df, "character(0)")

Error in charToDate(x) : 
  character string is not in a standard unambiguous format

谢谢你的帮助。

knsnq2tg

knsnq2tg1#

我们可以用

library(dplyr)
df %>%
   mutate(across(where(is.character), ~ na_if(.x, "character(0)")))
afdcj2ne

afdcj2ne2#

这是一个基本的R方式。
1.当列是类"character"时,创建取值TRUE的逻辑索引;
1.在lapply的列上创建索引列表;
1.使用mapply将错误值更改为NA

i_chr <- sapply(df, is.character)
inx_list <- lapply(df[i_chr], \(x) x == "character(0)")
df[i_chr] <- Map(\(x, i) {is.na(x) <- i; x}, df[i_chr], inx_list)

相关问题