Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 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 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...