Error in eval(predvars, data, env) : object 'psu' not found

Hi there,
i'm getting an error below and failed after many searches. can someone helping me how to fix this problem?

error:
Error in eval(predvars, data, env) : object 'psu' not found

code:
nhanesDesign1 <-svydesign(id = ~psu,
strata = ~strata,
weights = ~persWeight,
nest = TRUE,
data = nhanesAnalysis)

The column psu is not in your dataset nhanesAnalysis.

it is there, but after these codes below, it has such problem:
nhanesAnalysis <- nhanesAnalysis %>%
mutate(gender = recode(gender, '1' = 0L,
'2' = 1L))

nhanesAnalysis <-as.factor(nhanesAnalysis$gender)

Can you provide a reproducible example?

1 Like

thanks, here are 20 observations in nhanesAnalysis. the last 3 are bmi.

age gender personweight mecweight psu strata bmi

1 42 2 17627.67 18234.74 2 126 20.3
2 32 2 22744.36 23557.16 1 125 28.2
3 45 1 96194.93 97001.99 1 125 24.1
4 30 2 36978.42 38680.53 1 124 26.6
5 37 2 34128.79 35348.44 1 122 25.5
6 42 1 155365.01 156668.50 2 124 25.5
7 39 2 29007.80 30343.02 2 129 27.2
8 45 2 15415.16 16341.92 1 133 35.2
9 44 2 21984.31 22031.51 2 124 45.3
10 37 2 73609.00 73157.09 1 120 35.3
11 30 1 46748.64 48195.03 1 130 27.0
12 31 2 131578.08 135210.78 1 130 27.8
13 41 1 22734.58 22668.56 2 125 40.7
14 35 1 24494.47 25463.37 1 120 31.1
15 40 1 29757.77 29280.86 1 132 30.7
16 30 2 22381.03 23411.22 1 120 27.4
17 42 2 20649.80 21360.94 2 130 34.4
18 32 2 59714.39 61363.03 2 125 23.9
19 38 2 12817.57 13606.80 2 121 21.8
20 37 1 30010.41 30870.78 2 126 22.9

after these codes, the error comes up

nhanesAnalysis <- nhanesAnalysis %>%
mutate(gender = recode(gender, '1' = 0L,
'2' = 1L))

nhanesAnalysis <-as.factor(nhanesAnalysis$gender)

nhanesDesign1 <-svydesign(id = ~psu,
strata = ~strata,
weights = ~persWeight,
nest = TRUE,
data = nhanesAnalysis)

this is an error as it overwrites your entire frame with only the value of gender.
as you already alter gender in the previous line, simply extend it to be a factor

(nhanesAnalysis <- nhanesAnalysis %>%
  mutate(gender = factor(recode(gender, '1' = 0L,
                         '2' = 1L))))
1 Like

It appears that you replaced the entire dataset with just the gender variable (now as a factor) from that data.

nirgrahamuk beat me by one minute.

1 Like

thanks, It works now.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.