R 如何使用特定条件在df中添加列
我有一个df,我正试图根据某个标准向它添加一列。这是dfR 如何使用特定条件在df中添加列,r,function,apply,R,Function,Apply,我有一个df,我正试图根据某个标准向它添加一列。这是df Nos trt species days date int1 int2 int3 int4 intleng_total batch 1 1 sun b3 30 2/25/13 2.73 3.50 24.35 NA 30.58 1 2 2 sun b3 30 2/25/13 2.96 8.78 17.61 NA 29.35
Nos trt species days date int1 int2 int3 int4 intleng_total batch
1 1 sun b3 30 2/25/13 2.73 3.50 24.35 NA 30.58 1
2 2 sun b3 30 2/25/13 2.96 8.78 17.61 NA 29.35 1
3 3 sun b3 30 2/25/13 3.77 3.28 25.28 NA 32.33 1
4 4 sun b3 30 2/25/13 3.18 3.61 33.61 NA 40.40 1
5 5 sun b3 30 2/25/13 5.34 2.57 20.24 NA 28.15 1
6 6 sun ein9 30 2/25/13 13.64 34.73 NA NA 48.37 1
7 7 sun ein9 30 2/25/13 27.94 30.57 NA NA 58.51 1
8 8 sun ein9 30 2/25/13 9.03 11.23 39.12 NA 59.38 1
9 9 sun ein9 30 2/25/13 16.88 30.73 NA NA 47.61 1
10 10 sun ein9 30 2/25/13 15.79 45.87 NA NA 61.66 1
这是我一直在尝试但没有成功的标准
apply(int_comb$species,2,function (x) {if x == "b3", int_comb$mutation = "wt"})
基本上,对于df$species==“b3”
中的所有这些值,我想创建一个名为Mutation
的列,并向其中添加wt
,以及我想添加phyB
的ein9
我能得到一些帮助吗
谢谢@upendra。没问题。对于多个替换,第二个更好。
df$Mutation <- c("phyB", "wt")[(df$species=="b3")+1] #assuming `species` column is `character` class.
#If not convert use `(as.character(df$species=="b3")+1`
df$Mutation
#[1] "wt" "wt" "wt" "wt" "wt" "phyB" "phyB" "phyB" "phyB" "phyB"
setNames(c("wt","phyB"), c("b3", "ein9"))[df$species]
# b3 b3 b3 b3 b3 ein9 ein9 ein9 ein9 ein9
# "wt" "wt" "wt" "wt" "wt" "phyB" "phyB" "phyB" "phyB" "phyB"