我有一个像这样的样本数据集'a':
> a
group marks upd class
1 T 2 up A
2 C 3 up <NA>
3 C 4 down B
4 T 5 up <NA>
5 T 6 down D
6 C 7 up <NA>
7 T 1 down <NA>
8 T 0 down G
这里对于每个组(T或C),'class'变量中有记录,其值为null。现在对于每个类都为null的每个组,我希望该组分别重命名为T-NULL或C-NULL。如果组(T或c)在'class'中有一些值,则组名应该是原样。我们如何在R中为此编写代码?
答案 0 :(得分:0)
试试这个:
assign_group = function(class,group){
if(is.na(class)){ new_group = paste0(group,"NULL")}else{new_group=paste0(a$group,"NULL")}
return(new_group)}
a$new_group = sapply(a$class,assign_group,a$group)
答案 1 :(得分:0)
这应该有效
ifelse(is.na(a$class),paste(a$group,"NULL",sep="-"),paste(a$group))
答案 2 :(得分:0)
使用dplyr方法:
require(dplyr)
b <- a %>% mutate(new_class = ifelse(group %in% c("T","C") & is.na(class),paste(group,"NULL",sep="-"),class)
或data.tables
require(data.table)
a[,':='(= ifelse(group %in% c("T","C") & is.na(class),paste(group,"NULL",sep="-"),class))]
答案 3 :(得分:0)
数组索引方法!
a$class[is.na(a$class)] <- paste0(a$group[is.na(a$class)],"-NULL")