0

I have two data frames which both have one column:

df1

Server
A
B
c
d

df2

Server
a
f
z
x

I need to check if df1$Server exists in df2$Server. If yes, I need to add a column in df1 and put 1 else put 0.

I have this code, I think the algorithm is right but it does not seem to be working. Any input is appreciated.

for (i in 1:nrow(df1)) {
    if (df1[i,1] %in% row.names(df2)) {
        df1[i,2]<-c(1)
    } else{
        df1[i,2]<-(0)
    }
}
4

2 に答える 2

2

It's simpler than you're making it:

df1$LogicalColumn <- as.numeric(df1$Server==df2$Server)

This will sequence along each column and check for pairwise equality.

df1$LogicalColumn <- as.numeric(df1$Server %in% df2$Server)

This will check all values of df2's column for each value of df1$Server. If it really is the rownames you're concerned with (why?), replace df2$Server with rownames(df2) in either context.

于 2013-01-03T15:46:59.057 に答える
0

The default row names will be numbers, unless you have assigned them:

  Server
1      a
2      b
3      c
4      d
5      e

> row.names(df3)
[1] "1" "2" "3" "4" "5"

What you want is to compare against the values, not the names of the rows:

for (i in 1:nrow(df1)) {
  if (df1[i,1] %in% df2$Server) {
    df1[i,2]<-c(1)
  } else{  
    df1[i,2]<-(0)
  }            
}
于 2013-01-03T15:58:33.433 に答える