Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

r - 从另一个数据框替换数据框的列值(Replacing column values of dataframe from another dataframe)

I have two dataframes df1 and df2 both of same column numbers.

(我有两个相同的列号的数据框df1和df2。)

I want to replace all the column values of df1 with corresponding first row value from df2 columns.

(我想用df2列中的相应第一行值替换df1的所有列值。)

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

Is there a better way of doing this?

(有更好的方法吗?)

Please suggest the way forward.

(请提出前进的方向。)

  ask by Abhishek Kulkarni translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...