Replicate column values ​​row by row

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 am trying to replicate V3 values ​​across the entire string, 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?

Thank you very much in advance.

+4
source share
1 answer

You can use base-R syntax:

# to overwrite
df1[] <- df1$V3 

# to make a new table
df2   <- copy(df1)
df2[] <- df1$V3 

I think most data.table-ish is the way to change so many columns 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 a few 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
+8
source

Source: https://habr.com/ru/post/1599349/


All Articles