如果列有一个字符串,如“apple”,那么另一列值=“red”

时间:2016-07-09 07:31:01

标签: r

df1 <- data.frame(a=c("apple","computer,mouse","mac,pen","light"),b=c(2011,2012,2013,2014))

col1 <- rep(NA,4),df1<- (df1,col1)

如果df1[i]中的行为apple,则col1[i]为红色

我不知道如何使用函数匹配字符串。

2 个答案:

答案 0 :(得分:1)

我们可以使用grep在'a'列中找到'apple',用它来更新'col1'。

df1$col1[grep("apple", df1$a)] <- "red"
df1
#               a    b col1
#1          apple 2011  red
#2 computer,mouse 2012 <NA>
#3        mac,pen 2013 <NA>
#4          light 2014 <NA>

我会假设OP的代码

df1 <- cbind(df1, col1)

答案 1 :(得分:1)

假设OP的输入如下

 df1<- structure(list(a = structure(c(1L, 2L, 4L, 3L), .Label = c("apple", 
"computer,mouse", "light", "mac,pen"), class = "factor"), b = c(2011, 
2012, 2013, 2014), col1 = c(NA, NA, NA, NA)), .Names = c("a", 
"b", "col1"), row.names = c(NA, -4L), class = "data.frame")

可能的选项如下

index <- which(df1$a == "apple") 
df1$col1[index] <- "red"

> df1
#               a    b col1
#1          apple 2011  red
#2 computer,mouse 2012 <NA>
#3        mac,pen 2013 <NA>
#4          light 2014 <NA>