Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 204771

R Get Sum of Column

$
0
0

I have a simple dataframe in R

df1 <- data.frame(
  questionID = c(1,1,3,4,5,5),
   userID = c(101, 101, 102, 101, 102,101),
   Value=c(10,20,30,40,50,10))

The basic idea is to have a column that indicates the sum of value for a user on questions they asked before (lower number questions).

I tried using this function (after trying the pipe of sum which just gave errors about non-numeric that everybody seems to face)

f2 <- function(x){
     Value_out <- filter(df1,questionID<x['questionID'] & userID == x['userID'] ) %>%
       select(Value) %>%
       summarize_if(is.numeric, sum, na.rm=TRUE)
}

out=mutate(df1,Expert=apply(df1, 1,f2))

While this works if you print it out, the Expert column is saved as a list of dataframes. All I want is an int or numeric of the sum of Value. Is there anyway to do this? By the way, yes, I've looked all over for ways to do this, with most answers just summarizing the column in a manner that won't work for me.


Viewing all articles
Browse latest Browse all 204771

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>