R 使用 if else 逻辑为新列赋值
R use if else logic to assign value to new column
我需要创建一个新列,该列基于在列中找到的三个可能值之一。
规则如下:
If it has c somewhere in it, the new column should be assigned "third"
If it has b, but not c somewhere in it, the new column should be assigned "second"
If it has a but not b or c somewhere in it, the new column should be assigned "first"
这是我的示例代码
x <- c('a,b,c', 'a', 'a,b')
myLetters <- data.frame(x)
setnames(myLetters, "theLetter")
sapply(myLetters$, theLetter, function(x)
if ('c' %in% myLetters$theLetter) {
myLetters$letterStatus <- "third"
} else if ('b' %in% myLetters$theLetter) {
myLetters$letterStatus <- "second"
} else if ('a' %in% myLetters$theLetter) {
myLetters$letterStatus <- "first"
}
)
根据 myLetters$letterStatus 的示例数据,这是我想要的每一行的数据:
Row 1: third
Row 2: first
Row 3: second
目前我得到 "first" "first" "first" 但我不明白为什么。
你知道我如何解决这个问题以及为什么我每一行都排在第一位吗?
谢谢
使用矢量化(R 给我们的礼物)获得结果:
x <- c('a,b,c', 'a', 'a,b')
myLetters <- data.frame(x)
# myLetters
# x
# 1 a,b,c
# 2 a
# 3 a,b
myLetters$x1 = ifelse(grepl("c",myLetters$x), "third", ifelse(grepl("b",myLetters$x),"second", "first"))
我需要创建一个新列,该列基于在列中找到的三个可能值之一。
规则如下:
If it has c somewhere in it, the new column should be assigned "third"
If it has b, but not c somewhere in it, the new column should be assigned "second"
If it has a but not b or c somewhere in it, the new column should be assigned "first"
这是我的示例代码
x <- c('a,b,c', 'a', 'a,b')
myLetters <- data.frame(x)
setnames(myLetters, "theLetter")
sapply(myLetters$, theLetter, function(x)
if ('c' %in% myLetters$theLetter) {
myLetters$letterStatus <- "third"
} else if ('b' %in% myLetters$theLetter) {
myLetters$letterStatus <- "second"
} else if ('a' %in% myLetters$theLetter) {
myLetters$letterStatus <- "first"
}
)
根据 myLetters$letterStatus 的示例数据,这是我想要的每一行的数据:
Row 1: third
Row 2: first
Row 3: second
目前我得到 "first" "first" "first" 但我不明白为什么。
你知道我如何解决这个问题以及为什么我每一行都排在第一位吗?
谢谢
使用矢量化(R 给我们的礼物)获得结果:
x <- c('a,b,c', 'a', 'a,b')
myLetters <- data.frame(x)
# myLetters
# x
# 1 a,b,c
# 2 a
# 3 a,b
myLetters$x1 = ifelse(grepl("c",myLetters$x), "third", ifelse(grepl("b",myLetters$x),"second", "first"))