Hi there,
I have a data frame in a long format, containing multiple records by individual, corresponding to multiple eating occasions (e.g breakfast, snack, etc.) along with sodium intake in each occasion (see data set below). Then I convert it to a long format, so that each eating occasion is a different variable. Finally, I compute the mean of sodium by breakfast. See code below:
library(tidyr)
mydat = read.csv(file="…MyFile.csv")
#Transposing form long to wide format
mydat.SOD = as.data.frame(pivot_wider(mydat,
names_from = food.occasion,
values_from = SOD))
mydat.SOD[is.na(mydat.SOD)] = 0
#Renaming
names(mydat.SOD)[names(mydat.SOD) == "Breakfast"] = "SOD.brf"
names(mydat.SOD)[names(mydat.SOD) == "Lunch/Brunch"] = "SOD.lun"
names(mydat.SOD)[names(mydat.SOD) == "Dinner"] = "SOD.din"
names(mydat.SOD)[names(mydat.SOD) == "Snack"] = "SOD.snk"
names(mydat.SOD)[names(mydat.SOD) == "Drink"] = "SOD.drk"
mean(mydat.SOD$SOD.brf)
This code works perfectly. However, when I create a function to run this code multiple times (i.e. other nutrients), the code give me an error. Please, see the code below.
myF = function(nutrient){
#Transposing form long to wide format
mydat.nutrient = as.data.frame(pivot_wider(mydat,
names_from = food.occasion,
values_from = nutrient))
mydat.nutrient[is.na(mydat.nutrient)] = 0
#Renaming
names(mydat.nutrient)[names(mydat.nutrient) == "Breakfast"] = "nutrient.brf"
names(mydat.nutrient)[names(mydat.nutrient) == "Lunch/Brunch"] = "nutrient.lun"
names(mydat.nutrient)[names(mydat.nutrient) == "Dinner"] = "nutrient.din"
names(mydat.nutrient)[names(mydat.nutrient) == "Snack"] = "nutrient.snk"
names(mydat.nutrient)[names(mydat.nutrient) == "Drink"] = "nutrient.drk"
mean(mydat.nutrient$nutrient.brf)
}
myF(SOD)
Error: object 'SOD' not found
Run rlang::last_error()
to see where the error occurred.
Can you please advise?
Thank you.
Please, see the data set I'm using below.
ID | food.occasion | SOD |
---|---|---|
1 | Breakfast | 248.8 |
1 | Lunch/Brunch | 707.6 |
1 | Dinner | 424.8 |
1 | Snack | 2.3 |
1 | Drink | 11.7 |
2 | Breakfast | 824.7 |
2 | Lunch/Brunch | 511.8 |
2 | Dinner | 1813.3 |
2 | Snack | 166.8 |
2 | Drink | 102.2 |
3 | Lunch/Brunch | 1108.1 |
3 | Dinner | 179.6 |
3 | Drink | 19.6 |
4 | Breakfast | 332.8 |
4 | Lunch/Brunch | 1030.9 |
4 | Dinner | 109 |
5 | Breakfast | 300.1 |
5 | Lunch/Brunch | 150.6 |
5 | Dinner | 1896.9 |
5 | Drink | 23.4 |
Additional relevant information:
OS: Windows 10 (64-bit)
R version: 3.6.2
R studio version: 3.5