Golden Jiang Golden Jiang - 3 months ago 23
R Question

Warnings when perform cross tabulation using with()?

I am trying to perform cross tabulation in R and calculate the means.

Firstly I selected variables and created a new data frame:

seed <- ruk_trial$Ruk_seed_input #integer
soilec <- ruk_trial$Ruk_soilEC #num
ruk_trial$code_smoo[ruk_trial$code_smoo == 0] <- 'US'
ruk_trial$code_smoo[ruk_trial$code_smoo == 1] <- 'LS'
ruk_trial$code_smoo[ruk_trial$code_smoo == 2] <- 'HS'
zones <- ruk_trial$code_smoo #chr
netincome <- ruk_trial$NetIncome #num
yield <- ruk_trial$Dry_yield #num
ruk_df <- as.data.frame(cbind(seed,soilec,zones,netincome,yield))


Then I use with():

with(ruk_df, tapply(netincome, list(zones=zones, seed=seed), mean))


But it turns out:

seed
zones 105 120 75 90
HS NA NA NA NA
LS NA NA NA NA
US NA NA NA NA
There were 12 warnings (use warnings() to see them)

> warnings()
Warning messages:
1: In mean.default(X[[i]], ...) :
argument is not numeric or logical: returning NA


If I use the original dataset, it works:

> cross.tab<- with(ruk_trial, tapply(netincome, list(zones=zones,seed=seed), mean))


Can anyone tell me what causes the warnings?

Answer

Try this:

  ruk_df <- data.frame(seed,soilec,zones,netincome,yield, stringsAsFactors=FALSE)