2

So the data goes like this.

  1. SalesData is a data.frame.
  2. SalesData$Day1 is numeric column including sales data of each member on first day. Same goes for $Day2, $Day3 ... $Day50

I'm trying to make a new column with 50 numeric data, sum of each day's sale, by using loop.

I tried

for (i in 1:50)
{SalesData$Dailysum[i] <- sum(SalesData$get(colnames(SalesData)[i]))

Error: attempt to apply non-function

apparently I can't use get(colnames(SalesData)[i] to extract specific header.

SalesData$colnames(SalesData)[i] 

didn't work either.

Is there any way to use loop to extract header, and use it for loop?

  • Do you just want `colSums(SalesData)`? – Andrew Gustar May 20 '21 at 17:18
  • 1
    @AndrewGustar I tried it, but unfortunately it is not applicable since SalesData$names is a character column including sales team's name. It works perfectly after I tried deleting $names column, though. Thank you for help. – Eliyah Jung May 20 '21 at 17:32
  • Hi, could you provide a minimal example reproducing the format of your data ? See https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610 – Gowachin May 21 '21 at 16:15

1 Answers1

1

We can just do instead of get as it works with either numeric index or column names

for(i in 1:50)
  SalesData$Dailysum[i] <- sum(SalesData[[i]], na.rm = TRUE)

In tidyverse, we could also do with summarise while checking if the column type is numeric or not

library(dplyr)
SalesData %>%
    summarise(across(where(is.numeric), sum, na.rm = TRUE))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Wow! it works! Thank you! May I ask my code didn't work? – Eliyah Jung May 20 '21 at 17:19
  • @EliyahJung your code didn't work because you are using `get` on the column names with `$`. 1) `get` is not needed, 2) use `[[` for subsetting from an object name because `$` look for literal evaluation i.e. ` SalesData[[names(SalesData)[1]]]` work. Regarding, `get`, it looks for the object in the global env, while the column name is only available in the env of the dataset SalesData – akrun May 20 '21 at 19:12