给出以下数据框:
df1 <- data.table( V1=c(0,0,0,0),V2=c(0,0,0,0),V3=c(0,2,0,2))
df1
V1 V2 V3
1: 0 0 0
2: 0 0 2
3: 0 0 0
4: 0 0 2
我试图在整行上复制V3的值,以便:
df2
V1 V2 V3
1: 0 0 0
2: 2 2 2
3: 0 0 0
4: 2 2 2
我怎样才能做到这一点?
非常感谢提前。
答案 0 :(得分:8)
您可以使用base-R语法:
# to overwrite
df1[] <- df1$V3
# to make a new table
df2 <- copy(df1)
df2[] <- df1$V3
我认为修改这么多列的最多data.table-ish方法是使用set
:
# to overwrite
for (j in setdiff(names(df1),"V3")) set(df1, j = j, value = df1$V3)
# to make a new table -- simple extension
最后,还有来自@akrun,@ DavidArenburg和@VeerendraGadekar的其他一些好主意:
# to overwrite
df1[, (1:ncol(df1)) := V3] # David/Veerendra
# to make a new table
df2 <- setDT(rep(list(df1$V3), ncol(df1))) # akrun
df2 <- df1[, rep("V3",ncol(df1)), with = FALSE] # David