Reputation: 11
I have this dataframe
a <- data.frame(b = c(1,2,3,4,5,6),
d = c(2,4,6,8,10,12))
I want to make a make another row f which would be (d-b). How can I do this using a fucntion? I tried
new_a <- function(data, col1, col2){
data$f <- data$col2 - data$col1
return(data)
}
which gave " Error in $<-.data.frame
(*tmp*
, c, value = integer(0)) :
replacement has 0 rows, data has 5 "
I also tried
new_a = function(data, col1, col2) {
data$f = data[col1] - data[col2]
return(data)
}
but this table wont name the new row as "f"
Would appreciate the help.
Upvotes: 0
Views: 29
Reputation: 808
In your data frame, if there are no columns named col1
and col2
, you will get that error. Using your example and changing your new_a
function worked as follows,
new_a <- function(data){
data$f <- data$d - data$b
return(data)
}
Upvotes: 1