将整数更改为 data.frame 中的特定字符串

Change an integer into a specific string in a data.frame

我有一个包含两列的数据框。第二列仅包含整数。更准确地说,它包含 0、1、2、3 和一些 NA。像这样:

id1    0
id2    1
id3    0
id4    2
id5    3
id6    1
id7    2
id8    NA

我要搜索的是将 0 更改为 ZZT、将 1 更改为 ZZU 等的命令。 NA 应该保留为 NA。这怎么行?

我尝试将 for 循环与一些 if 语句结合使用,但这不起作用。我知道这种改变想法在 R 中很容易,但我的大脑似乎有一个障碍。

这样做就可以了:

  # Setup an example data frame
  df <- data.frame(id=c("id1","id2","id3","id4","id5","id6","id7","id8"),
                 val=c(0,1,0,2,3,1,2,NA))

  # Now setup the translation vector - essentially a lookup table
  trans <- c("ZZT","ZZU","ZZV","ZZW",NA)
  names(trans) <- c(0,1,2,3,NA)

  # Now translate the values into a new column and print it out 
  df$nval <- trans[ as.character(df$val) ]
  df$nval
  # [1] "ZZT" "ZZU" "ZZT" "ZZV" "ZZW" "ZZU" "ZZV" NA 

它使用命名向量作为查找 table。括号实际上是一个子集运算符,当您使用字符向量访问它时,它会使用向量名称进行子集化。

如果您不明白,请阅读 Hadley Wickham 关于子集化的精彩 "Advanced R" 章节。 http://adv-r.had.co.nz/Subsetting.html

使用 match 在替换值向量中创建索引向量是一种 "canonical" R 方法(使用 Mike Wise 的示例)

c("ZZT","ZZU","ZZV","ZZW",NA)[ match( df1$val, c(0,1,2,3,NA))]
[1] "ZZT" "ZZU" "ZZT" "ZZV" "ZZW" "ZZU" "ZZV" NA

如果你想替换它们 "in place"(通常是一个危险的选择)那么这可能有效:

df$val <- c("ZZT","ZZU","ZZV","ZZW",NA)[ match( df$val, c(0,1,2,3,NA))]

您可以使用 plyr 包中的 mapvalues 函数映射值。使用 Mike Wise 回答中的示例数据:

library(plyr)
df$val2 <- mapvalues(df$val,
                           from = c(0,1,2,3,NA),
                           to = c("ZZT", "ZZU", "ZZV", "ZZW", NA))

如果您已经加载了 dplyr 包(plyr 的后继包),请使用plyr::mapvalues() 调用此函数,因为在 dplyr 之上加载 plyr 是有问题的。