[英]R: Replace values of dataframe from another using row/column
I have a dataframe
that I want to replace some of its values using another dataframe
which I have row
, column
, and value
information. 我有一个dataframe
,我想使用另一个具有row
, column
和value
信息的dataframe
替换其某些value
。
dat <- data.frame(Age = c(19,22,32,24),Names = c("Bobby","Mary","Bill","Chuck"), Sport = c("Golf","Tennis","Football","Soccer"))
Age Names Sport
19 Bobby Golf
22 Mary Tennis
32 Bill Football
24 Chuck Soccer
valuesreplace <- data.frame(row = c(1,3), column = c(3,1), value = c("Basketball","18"))
row column value
1 3 Basketball
3 1 18
The result should be the following: 结果应为以下内容:
Age Names Sport
19 Bobby Basketball
22 Mary Tennis
18 Bill Football
24 Chuck Soccer
We need to first convert the factor
to character
(use stringsAsFactors = FALSE
while constructing both data.frames) and then use pass a matrix
of row/column index select the values of 'dat' and assign values from 'valuesreplace' column 'value' 我们需要首先将factor
转换为character
(在构造两个data.frames时使用stringsAsFactors = FALSE
),然后使用传递行/列索引matrix
选择“ dat”的值,并从“ valuesreplace”列“ value”中分配值
dat[as.matrix(valuesreplace[1:2])] <- valuesreplace$value
dat
# Age Names Sport
#1 19 Bobby Basketball
#2 22 Mary Tennis
#3 18 Bill Football
#4 24 Chuck Soccer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.