-----Original Message-----
From: R-help <r-help-bounces at r-project.org> On Behalf Of David L Carlson
Sent: Sunday, February 17, 2019 1:49 AM
To: Eric Berger <ericjberger at gmail.com>; javad bayat
<j.bayat194 at gmail.com>
Cc: R mailing list <R-help at r-project.org>; r-help-owner at r-project.org
Subject: Re: [R] Problem with combining 2 data frame
This is another approach using match():
df1 = data.frame(x1 = letters[1:26],x2 = NA, stringsAsFactors=FALSE)
df2 = data.frame(x1 = letters[10:15],x2 = c("1a","2a","3a","4a","5a","6a"),
stringsAsFactors =FALSE)
df1$x2[match(df2$x1, df1$x1)] <- df2$x2
---------------------------------------------
David L. Carlson
Department of Anthropology
Texas A&M University
-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Eric Berger
Sent: Friday, February 15, 2019 11:43 PM
To: javad bayat <j.bayat194 at gmail.com>
Cc: R mailing list <R-help at r-project.org>; r-help-owner at r-project.org
Subject: Re: [R] Problem with combining 2 data frame
Hi Javad,
You have a number of problems with your code, such as:
1. you should set df1 and df2 without factors 2. you define a function f(x,y) but
the body of the function never refers to x and y
The following code does what I think you are looking for:
df1 = data.frame(x1 = letters[1:26],x2 = NA,stringsAsFactors = FALSE)
df2 = data.frame(x1 = letters[10:15],x2 = c("1a","2a","3a","4a","5a","6a"),
stringsAsFactors = FALSE)
aa <- sapply( 1:nrow(df2), function(i) { df1$x2[ df1$x1==df2$x1[i] ] <<-
df2$x2[i] } )
HTH,
Eric
On Sat, Feb 16, 2019 at 4:11 AM javad bayat <j.bayat194 at gmail.com> wrote:
Dear R users;
I am trying to combine 2 dataframes with different rows, 26 and 6
rows. The first column of both dataframe has something in common, and
I want to compare the first column of the df1 with first column of the
df2 to see if they are same or not. Then if they were same, the second
column of the df1 fill by the value of the second column of df2.
df1 = data.frame(x1 = letters[1:26],x2 = NA)
df2 = data.frame(x1 = letters[10:15],x2 =
c("1a","2a","3a","4a","5a","6a"))
f = function(x,y){
for (i in 1:nrow(df1))
ifelse(df1$x1 == df2$x1, df1$x2==df2$x2, "NA")}
f(df1,df2)
Error in Ops.factor(df1$x1, df2$x1) : level sets of factors are
different
Is there anyone to help me to solve this problem?
Sincerely.
--
Best Regards
Javad Bayat
M.Sc. Environment Engineering
Alternative Mail: bayat194 at yahoo.com
[[alternative HTML version deleted]]