如何根据条件创建新变量

3

数据文件名:toys

假设我有以下数据框:

ID    Name
1     Green Ball
2     Red Ball
3     Blue Bat
4     Green Bat
5     Blue Ball
6     Ball
7     Bat

我想通过在名称中搜索颜色来添加一个新变量"Color"。
ID    Name           Color
1     Green Ball     Green
2     Red Ball       Red
3     Blue Bat       Blue
4     Green Bat      Green
5     Blue Ball      Blue
6     Ball           Other
7     Bat            Other

我从未使用过R语言,也不确定该如何开始。我尝试了以下内容但没有成功。

toys$Color <- (
if toys$Name = "Green", Color "Green"
else if toys$Name = "Red", Color "Red"
else if toys$Name = "Blue, Color "Blue"
else toys$Name = "Other"
)

我非常希望能够协助您解决这个问题。
谢谢。

你的实际示例是颜色吗?还是仅仅举个例子,然后你想要提取一个主列表中的值呢? - thelatemail
是的,这是颜色。基本上,“Name”列包含一个短语或描述。我想让新的“Color”列简单地搜索给定颜色列表,如果颜色在“Name”列中任何位置匹配,它应该将该颜色放入“Color”列。如果它发现“Name”列中没有匹配的颜色,则只需输出“其他”。这有帮助吗? - IronBat
你有检查我下面发布的解决方案吗? - akrun
2个回答

4
我们可以使用str_extract。创建一个包含所有颜色的向量('col1'),使用str_extract通过将'col1'作为单个字符串并用字符'|'分隔来获取与'Name'中元素匹配的子字符串。将输出中的NA元素替换为'Other'以创建新列'Color'。
library(stringr)
col1 <- c("Green", "Red", "Blue")
v1 <- str_extract(toys$Name, paste(col1, collapse="|"))
v1[is.na(v1)] <- "Other"
toys$Color <- v1
toys
#  ID       Name Color
#1  1 Green Ball Green
#2  2   Red Ball   Red
#3  3   Blue Bat  Blue
#4  4  Green Bat Green
#5  5  Blue Ball  Blue
#6  6       Ball Other
#7  7        Bat Other

1

有限数量的颜色,因此您可以创建这些颜色的列表。然后使用来自包stringrstr_detect,您需要安装该包。该函数允许您检测字符串中模式(颜色)的存在。我们使用循环将此函数应用于df中的每个元素。

df <- as.data.frame(c("Green Ball", "Ball", "Red Ball", "Blue Bat", "White cake", "Deep Purple"))
colnames(df) <- "Items"
colors <- c("Green", "Red", "Blue", "Purple", "Yellow", "White", "Black", "Pink")

library(stringr)
result <- NULL
for (i in 1:NROW(df)){
  true.false <- str_detect(as.character(df[i,1]), colors)
  col <- ifelse(any(true.false), colors[true.false], "No color")
  result <- c(result, col)
}

df$Colors <- result
df
        Items   Colors
1  Green Ball    Green
2        Ball No color
3    Red Ball      Red
4    Blue Bat     Blue
5  White cake    White
6 Deep Purple   Purple

替代方案: 您也可以在上述for循环中使用此方法。

library('stringi')
stri_detect_fixed("Deep Purple", c("Purple", "Blue"))
#[1]  TRUE FALSE

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接