user124123
user124123

Reputation: 1683

Add new column to data frame, taking existing values within range

I was wondering if anyone knows a simple way to create a new column in a data frame, taking data from an existing column, within a certain range.

For example, I have this data frame

range  col1 
1      5
2      4
3      9
4      5
5      2
6      8
7      9

I would like to create col2 using the data in col1, and have col2 take values above the range 3

range  col1   col2
1      5       0
2      4       0
3      9       0
4      5       5
5      2       2
6      8       8
7      9       9

I have tried

data$col2 <- data$col1 [which(data$range > 3)) ]
data$col2 <- subset ( data$col1 , data$range >3 ) 

However both of these produce error:

replacement has 4 rows, data has 7

Any help greatly appreciated

Upvotes: 0

Views: 1593

Answers (2)

talat
talat

Reputation: 70266

You can do it even without ifelse here:

data$new <- with(data, (range > 3) * col1)
data
#  range col1 new
#1     1    5   0
#2     2    4   0
#3     3    9   0
#4     4    5   5
#5     5    2   2
#6     6    8   8
#7     7    9   9

Upvotes: 3

akrun
akrun

Reputation: 887128

Try ifelse

 transform(data, col2=ifelse(range >3, col1, 0))
 #   range col1 col2
 #1     1    5    0
 #2     2    4    0
 #3     3    9    0
 #4     4    5    5
 #5     5    2    2
 #6     6    8    8
 #7     7    9    9

Upvotes: 1

Related Questions