Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replicate values of column along rows

Tags:

r

data.table

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.

like image 401
David Avatar asked Feb 09 '23 12:02

David


1 Answers

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
like image 87
Frank Avatar answered Feb 12 '23 05:02

Frank