R语言 创建合并两个分类列的新分类列

ymzxtsji  于 2022-12-27  发布在  其他
关注(0)|答案(2)|浏览(130)

我有这个df

df <- data.table(id=c(1,2,3,4,5,6,7,8,9,10),
                 var1=c(0,4,5,6,99,3,5,5,23,0),
                 var2=c(22,4,6,25,6,70,75,23,24,21))

我想设立第三栏:

df <- data.table(id=c(1,2,3,4,5,6,7,8,9,10),
                 var1=c(0,4,5,6,99,3,5,5,23,0),
                 var2=c(22,4,6,25,6,70,75,23,24,21),
                 var3=c("0_22","4_4","5_6","6_25","99_6","3_70","5_75","5_23","23_24","0_21"))

其中每个单元格的值将是“var 1下划线var 2”。Var 1和Var 2是分类变量,因为它们表示药物。Var 3将表示药物的组合。
我该怎么做呢?
谢谢!

iklwldmw

iklwldmw1#

加载程序包

library(data.table)
library(dplyr)

创建 Dataframe

df <- data.table(
  id = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
  var1 = c(0, 4, 5, 6, 99, 3, 5, 5, 23, 0),
  var2 = c(22, 4, 6, 25, 6, 70, 75, 23, 24, 21)
)

添加新变量

通过dplyr包和sprintf
df <- df %>% 
  mutate(var3 = sprintf("%d_%d", var1, var2))
通过薄膜 Package 和粘贴0
df <- df %>% 
  mutate(var3 = paste0(var1, "_", var2))
通过基本包和sprintf
df$var3 <- sprintf("%d_%d", df$var1, df$var2)
通过基础 Package 和糊剂0
df$var3 <- paste0(df$var1, "_", df$var2)
p3rjfoxz

p3rjfoxz2#

正如@Wimpel所说,解决方案是df$var3〈- paste(df$var1,df$var2,sep =“_”)谢谢!!

相关问题