我是R的新手,有其他典型语言的经验,在创建一些功能方面有困难。我得到了一个错误:
Error: Assigned data `*vtmp*` must be compatible with existing data.
x Existing data has 5114 rows.
x Assigned data has 0 rows.
i Only vectors of size 1 are recycled
这是密码。有人知道怎么解决这个问题吗?
print("***********************************************************************************")
#Load the packages
library(descr)
library(Hmisc)
library(ggplot2)
#Load AddHealthIV Dataset
data<-addhealth4
########################Functions########################################
missingDatatoNA <- function(variable, Missing) {
for(i in 0:3){
data$variable[data$variable==3]<-NA
}
return(data$variable)
}
####################Explanatory Variables################################
#o = openness to experience, c = conscientiousness, a = etc.
#will eventually make a master secondary variable for each trait
#* indicates necessity for reversal of codes
data$e1<-data$H4PE1 #*
data$e1<-missingDatatoNA(data$e1, c(6,8,"."))
下面是数据集的链接:https://drive.google.com/file/d/1wTtvsilxR9-RjPPVEFg_tgbBc8MTeG6i/view?usp=sharing
这是我的心理统计课程,你可以相信它,我不知道如何安全地分享它。
发布于 2022-01-09 01:52:13
在将向量data$e1
传递给函数时,不需要data$variable
。实际上,data$variable
是NULL
,因为(可能)在dataset data
中没有名称为variable
的列。这就是为什么你会犯错误。
可以用mtcars
作为示例数据来说明这一点,除了一些警告之外,这些数据还会产生您报告的相同的错误消息:
# Reproduce the issue
data <- tibble::as_tibble(mtcars)
missingDatatoNA <- function(variable, Missing) {
for (i in 0:3) {
data$variable[data$variable == 3] <- NA
}
return(data$variable)
}
data$e1 <- data$hp
missingDatatoNA(data$e1, c(6, 8, "."))
#> Warning: Unknown or uninitialised column: `variable`.
#> Warning: Unknown or uninitialised column: `variable`.
#> Error: Assigned data `*vtmp*` must be compatible with existing data.
#> x Existing data has 32 rows.
#> x Assigned data has 0 rows.
#> ℹ Only vectors of size 1 are recycled.
要解决问题,只需执行variable[variable==3] <- NA
# Solve the issue
missingDatatoNA_fixed <- function(variable, Missing) {
for (i in 0:3) {
variable[variable == 3] <- NA
}
return(variable)
}
missingDatatoNA_fixed(data$e1, c(6, 8, "."))
#> [1] 110 110 93 110 175 105 245 62 95 123 123 180 180 180 205 215 230 66 52
#> [20] 65 97 150 150 245 175 66 91 113 264 175 335 109
https://stackoverflow.com/questions/70637471
复制相似问题