简体   繁体   中英

Replacing column values of dataframe from another dataframe

I have two dataframes df1 and df2 both of same column numbers. I want to replace all the column values of df1 with corresponding first row value from df2 columns.

df1$col1<-df2$col1[1]
.
.
.
df1$col17<-df2$col17[1]

Is there a better way of doing this? Please suggest the way forward.

You could directly assign the values by using []

df1[] <- df2[1, ]
df1
#  col1 col2 col3
#1    1    2    5
#2    1    2    5
#3    1    2    5
#4    1    2    5
#5    1    2    5

data

df1 <- data.frame(col1 = 1:5, col2 = 2:6, col3 = 3:7)
df2 <- data.frame(col1 = 1:3, col2 = 2:4, col3 = 5:7)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM