修改:建议的代码有效,所以总计:
MyData$Numbers_2=with(MyData, ifelse(Numbers %in% MyVector,
paste0("L_N", Numbers),
paste0("L_", Numbers)))
这会添加一个包含新(字符)值的列。
我想根据在向量中找到值的条件,为数据帧的列中的每个值添加一个特定的字符串。
#Create Dataframe
MyData=data.frame(Numbers=c(85,84,7,9,82,5,81,80,10))
MyVector=c("80","81","82","83","84","85")
# for Loop with if else condition
for (Nr in MyVector) {MyData$Numbers_2=as.character(MyData$Numbers)
if(is.element(Nr,MyData$Numbers_2)) {MyData$Numbers_2= paste("L_N",MyData$Numbers_2, sep = "")}
else {MyData$Numbers_2= paste("L_",MyData$Numbers_2, sep = "")}
}
基本上,我想得到这样的结果: L_N85,L_N84,L_7,L_9等 但我得到的是:L_N85,L_N84,L_N7,L_N9 它将L_N添加到列中的每个值,而不仅仅是特定值。如何更改我的代码?
答案 0 :(得分:1)
我们可以使用矢量化for
if/else
循环或ifelse
with(MyData, ifelse(Numbers %in% MyVector, paste0("L_N", Numbers), paste0("L_", Numbers)))
#[1] "L_N85" "L_N84" "L_7" "L_9" "L_N82" "L_5" "L_N81" "L_N80" "L_10"
或case_when
dplyr
library(dplyr)
MyData %>%
mutate(Numbers_2 = case_when(Numbers %in% MyVector ~ paste0("L_N", Numbers),
TRUE ~ paste0("L_", Numbers)))