Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 当第二个数据帧中存在匹配值时,替换数据帧列的值_R - Fatal编程技术网

R 当第二个数据帧中存在匹配值时,替换数据帧列的值

R 当第二个数据帧中存在匹配值时,替换数据帧列的值,r,R,我想用df2$replacement中的值替换df1$colB的值,其中df1$colB等于df2$matches df1 <- data.frame(colA = 1:10, colB = letters[1:10]) df2 <- data.frame(matches= letters[4:1], replacement= LETTERS [4:1]) 我希望避免此任务的for循环解决方案。您可以在df1和df2上执行合并,然后用替换替换colB值: library(dply

我想用
df2$replacement
中的值替换
df1$colB
的值,其中
df1$colB
等于
df2$matches

df1 <- data.frame(colA = 1:10, colB = letters[1:10])

df2 <- data.frame(matches= letters[4:1], replacement= LETTERS [4:1])

我希望避免此任务的for循环解决方案。

您可以在
df1
df2
上执行
合并
,然后用
替换
替换
colB
值:

library(dplyr)
merge(df1, df2, by.x = "colB", by.y = "matches", all.x = T) %>% 
  mutate(colB = ifelse(!is.na(replacement), replacement, colB)) %>%  
  select(colA, colB)
   colA colB
1     1    A
2     2    B
3     3    C
4     4    D
5     5    e
6     6    f
7     7    g
8     8    h
9     9    i
10   10    j

您可以在
df1
df2
上执行
merge
,然后用
replacement
替换
colB
值:

library(dplyr)
merge(df1, df2, by.x = "colB", by.y = "matches", all.x = T) %>% 
  mutate(colB = ifelse(!is.na(replacement), replacement, colB)) %>%  
  select(colA, colB)
   colA colB
1     1    A
2     2    B
3     3    C
4     4    D
5     5    e
6     6    f
7     7    g
8     8    h
9     9    i
10   10    j

您可以在base R中使用
chartr
函数

# read in data with character vectors, not factors
df1 <- data.frame(colA = 1:10, colB = letters[1:10], stringsAsFactors=F)
df2 <- data.frame(matches= letters[4:1], replacement= LETTERS [4:1], stringsAsFactors=F)
df3 <- data.frame(colA =1:10, colB = c(LETTERS[1:4],letters[5:10]), stringsAsFactors=F)

# replace the characters with the desired characters
df1$colB <- chartr(paste(df2$matches, collapse=""), 
                   paste(df2$replacement, collapse=""), df1$colB)
#使用字符向量而非因子读入数据

df1您可以在base R中使用
chartr
函数

# read in data with character vectors, not factors
df1 <- data.frame(colA = 1:10, colB = letters[1:10], stringsAsFactors=F)
df2 <- data.frame(matches= letters[4:1], replacement= LETTERS [4:1], stringsAsFactors=F)
df3 <- data.frame(colA =1:10, colB = c(LETTERS[1:4],letters[5:10]), stringsAsFactors=F)

# replace the characters with the desired characters
df1$colB <- chartr(paste(df2$matches, collapse=""), 
                   paste(df2$replacement, collapse=""), df1$colB)
#使用字符向量而非因子读入数据
df1