简体   繁体   English

R:使用行/列替换另一个数据框的值

[英]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 ,我想使用另一个具有rowcolumnvalue信息的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.

相关问题 使用另一数据框的一行中的值替换一个数据框的一列中的所有值(按行名和列名匹配) - Replace all values in a column of one dataframe using values in a row of another dataframe (matching by row name and column name) 与 R 中另一个 dataframe 中的列匹配时,替换 dataframe 中的列中的值 - Replace values in column of a dataframe when matching to column in another dataframe in R 使用另一个数据帧的行中的值替换一个数据帧的列中的所有值(按行名称和列名称匹配),替换为字符 - Replace all values in column of one dataframe using values in row of another dataframe (matching by row name&column name), replacement is characters 从R数据框中的列替换部分值 - Replace partial values from a column in a R dataframe 如何使用R中另一个数据帧的值填充列 - How to fill a column using values from another dataframe in R 使用 dplyr 有条件地将一列/行中的值替换为另一行/列中的值 - Conditionally replace values in one column/row with values from another row/column using dplyr 使用Apply函数将基于数据框中月份的值替换为r中另一列中的值 - Replace values based on months in a dataframe with values in another column in r, using apply functions R - 在另一个数据帧的行中插入数据帧中的值,列名作为 ID - R - Insert values from dataframe in row of another dataframe with column names as ID 替换超出范围的值是指 r 中每一行的另一个 dataframe - Replace outrange values refer to another dataframe for each row in r 用另一数据框R的行替换一列中每次出现的因子变量 - Replace every occurrence of factor variable in one column with row from another dataframe R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM