Given the following data frame:
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
I seek to replicate the values of V3 along the entire row, so that:
df2
V1 V2 V3
1: 0 0 0
2: 2 2 2
3: 0 0 0
4: 2 2 2
How can I achieve this?
Many thanks in advance.
You could use base-R syntax:
# to overwrite
df1[] <- df1$V3
# to make a new table
df2 <- copy(df1)
df2[] <- df1$V3
I think the most data.table-ish way to modify so many columns is with set
:
# to overwrite
for (j in setdiff(names(df1),"V3")) set(df1, j = j, value = df1$V3)
# to make a new table -- simple extension
Finally, there are several other good ideas from @akrun, @DavidArenburg and @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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With