Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/google-chrome/4.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,使用R的新手,希望知道如何基于另一个数据帧中的数据在数据帧中创建新列。假设我有两个数据帧,由df1col2和df2col1中的字母“a”、“b”和“c”链接,如下所示: > col1<-c(1, 2, 3, 4) > col2<-c("a","b","c","c") > df1<-data.frame(col1, col2) > df1 col1 col2 1 1 a 2 2 b 3 3 c 4 4 c

使用R的新手,希望知道如何基于另一个数据帧中的数据在数据帧中创建新列。假设我有两个数据帧,由
df1
col2
df2
col1
中的字母“a”、“b”和“c”链接,如下所示:

> col1<-c(1, 2, 3, 4)
> col2<-c("a","b","c","c")
> df1<-data.frame(col1, col2)
> df1
  col1 col2
1    1    a
2    2    b
3    3    c
4    4    c
> c1<-c("a","b","c")
> c2<-c("Jim","Sue","Bob")
> c3<-c("abc","def","ghi")
> df2<-data.frame(c1,c2,c3)
> df2
  c1  c2 c3
1  a Jim abc
2  b Sue def
3  c Bob ghi
我已经尝试了
df1[“col3”]您需要合并()


键入?合并以查看其工作原理。

查看合并或匹配。我喜欢
dplyr
中的
left\u-join
。为了完整性起见,它应该是
merge(df1,df2,by.x=“col2”,by.y=“c1”)
谢谢@kliron,这显然合并了
df2
中的所有列。。。如何仅合并
df2
中指定的列
c2
?什么意思?这正是您在问题中想要的输出。如果在df2中有更多不需要的列(在问题中没有显示),只需将df2子集,只保留所需的列,然后将该数据帧合并到df1。您还可以将生成的df1子集,甚至通过如下方式将其设置为空来删除单个列:df1$unwantedColumn我发现了<此答案中仅添加了code>df1
c2
(除了
c2
的列名在您的问题中被称为
col3
。您可以使用
名称(结果)[3]更改此答案
> merge(df1, df2, by.x = "col2", by.y = "c1")
  col2 col1  c2
1    a    1 Jim
2    b    2 Sue
3    c    3 Bob
4    c    4 Bob
# this merges the two data frames and rebinds the result to df1 
df1 <- merge(df1, df2, by.x = "col2", by.y = "c1")
# This renames the "c1" column to "col3"
names(df1) <- c("col2", "col1", "col3")
# This rearranges the columns in the right order
df1 <- df1[,c(2,1,3)] 
 col1 col2 col3
1    1    a  Jim
2    2    b  Sue
3    3    c  Bob
4    4    c  Bob
> merge(df1, df2, by.x = "col2", by.y = "c1")
  col2 col1  c2
1    a    1 Jim
2    b    2 Sue
3    c    3 Bob
4    c    4 Bob