Woobin Yun
Woobin Yun

Reputation: 3

how can I store printed result from if statement as a dataframe?

I would like to set the printed result of if statement as a dataframe for later use.

For example,

if I run,

for(i in 1:nrow(user)){
 for(j in 1:nrow(user_info)){
     if(user[i,1]==user_info[j,1])
          df<-print(user_info[j,1:3])
  }
}

the console shows,

1 roles user guest
     1    1    15
2 roles user guest
     2    1    367
3 roles user guest
     3    1    648

and when I call 'df' it only shows the last result.

 roles user guest
   3     1     648

How can I store the full result as a dataframe if I want 'df' to be like this?

roles user guest
 1    1    15
 2    1    367
 3    1    648

In order to clarify the question, here is the sample data. I tried all comments but the problem is not solved yet..

user:

roles  action  created_at
  10      1     2016-08-01
  10      1     2016-08-01
  1       1     2016-08-01
  3       2     2016-08-01
  4       1     2016-08-01
  5       1     2016-08-01
  5       2     2016-08-02
  8       1     2016-08-02
  9       1     2016-08-02
  7       2     2016-08-02

user_info:

roles user guest
  1     1    15
  2     1    367
  3     14   42
  4     2    34
  5     4    2
  6     3    100
  7     23   32
  8     9    49  
  9     55   12
  10    8    291

Upvotes: 0

Views: 61

Answers (2)

Aditya
Aditya

Reputation: 2415

Can you try rbind?

for(i in 1:nrow(user)){
 for(j in 1:nrow(user_info)){
     if(user[i,1]==user_info[j,1])
          user_info<-print(user_info[j,1:3])
          df<-rbind(df,user_info)
  }
}

Upvotes: 0

djhurio
djhurio

Reputation: 5536

What about merging?

merge(user_info, user, by = "role")[, 1:3]

Upvotes: 1

Related Questions