Hello! I am trying to do a jackknife operation apparently. I have asked this question previously on stackoverflow and was redirected to an answer (courtesy of dave armstrong). However this doesn't work, and I now think several functions I wrote before didn't work for the same reason.
My initial question:
The answer:
When I try to run this code
countryedategroup2 %>% mutate(across(c(econw, forpolw, libauthw, demw, urbruralw, ethnicw, educationw, envprow, euintw, decentw), function(x)
map_dbl(seq_along(x), function(rn) mean(x[-rn])),
.names = "{.col}_mean"))
I get this error:
Error in
mutate()
:
In argument:across(...)
.
Caused by error inacross()
:
! Can't compute columneconw_mean
.
Caused by error inmap_dbl()
:
In index: 1.
Caused by error inh()
:
! error in evaluating the argument 'x' in selecting a method for function 'mean': object 'x' not found
Runrlang::last_error()
to see where the error occurred.
So I started stripping this code. I finally arrived at that:
countryedategroup2 %>% mutate(econwjack = map_dbl(seq_along(econw), function(rn) mean(econw[-rn])))
Which resulted in all Na values. Several for loops I wrote before also resulted in all Na values, but I thought I made a mistake in the code. I now think maybe there is a problem with data. What is the reason for that? When I do the calculation manually as below:
countryedategroup2 <- countryedategroup2 %>% mutate(
econwjack = c(mean(countryedategroup2$econw[which(countryedategroup2$econw!=countryedategroup2[1,22])], na.rm = TRUE),
mean(countryedategroup2$econw[which(countryedategroup2$econw!=countryedategroup2[2,22])], na.rm = TRUE),
mean(countryedategroup2$econw[which(countryedategroup2$econw!=countryedategroup2[3,22])], na.rm = TRUE),
mean(countryedategroup2$econw[which(countryedategroup2$econw!=countryedategroup2[4,22])], na.rm = TRUE),
mean(countryedategroup2$econw[which(countryedategroup2$econw!=countryedategroup2[5,22])], na.rm = TRUE),
mean(countryedategroup2$econw[which(countryedategroup2$econw!=countryedategroup2[6,22])], na.rm = TRUE),
mean(countryedategroup2$econw[which(countryedategroup2$econw!=countryedategroup2[7,22])], na.rm = TRUE)))
I get below result:
urbruralw_mean ethnichw_mean educationw_mean envprow_mean euintw_mean decentw_mean econwjack
1 4.587094 0.2378293 0.2020795 0.3101839 0.182376 0.1730582 0.4614283
2 4.587094 0.2378293 0.2020795 0.3101839 0.182376 0.1730582 0.5667689
3 4.587094 0.2378293 0.2020795 0.3101839 0.182376 0.1730582 NaN
4 4.587094 0.2378293 0.2020795 0.3101839 0.182376 0.1730582 NaN
5 4.587094 0.2378293 0.2020795 0.3101839 0.182376 0.1730582 0.1909023
6 4.587094 0.2378293 0.2020795 0.3101839 0.182376 0.1730582 0.5870974
7 4.587094 0.2378293 0.2020795 0.3101839 0.182376 0.1730582 0.5881766
I have 10 variables over 159 groups all including from 7 to 15 observations to be computed in this way so writing this manually is not an option. Thank you very much for your help!