1

我正在尝试重新编码,并且遇到了一个看起来很简单的障碍,但是在互联网上询问了很长时间后我无法弄清楚,所以我很感激你能提供的任何帮助。

我有一些包含 NA 的数据。我想使用这些数据重新编码,但继续遇到错误“下标分配中不允许使用 NA”。当我试图创建一个示例数据集时,我还遇到了一个警告,我没有“有意义的因素”。任何帮助,将不胜感激。

我的人造数据有三个变量:“var1”和“var2”(字符,有时缺失)和“var3”(数字)。我想创建第四个变量,如果 beta 大于零,则包含“var1”的值,如果 beta 小于零,则包含“var2”的值。如果 var1 或 var2 丢失,我希望新变量也丢失:

var1<-c("A","T",NA,"G","C")
var2<-c("G","A",NA,"A","G")
var3 <-c(-.1,3,-4,5,-3)
df=as.data.frame(cbind(var1,var2,var3))

df$newVar[df$var3>0]=df$var1[df$var3>0]
df$newVar[df$var3<0]=df$var2[df$var3<0]

我得到的是一堆红色:

df$newVar[df$var3>0]=df$var1[df$var3>0]
Error in df$newVar[df$var3 > 0] = df$var1[df$var3 > 0] : 
NAs are not allowed in subscripted assignments
In addition: Warning messages:
1: In Ops.factor(df$var3, 0) : > not meaningful for factors
2: In Ops.factor(df$var3, 0) : > not meaningful for factors
df$newVar[df$var3<0]=df$var2[df$var3<0]
Error in df$newVar[df$var3 < 0] = df$var2[df$var3 < 0] : 
NAs are not allowed in subscripted assignments
In addition: Warning messages:
1: In Ops.factor(df$var3, 0) : < not meaningful for factors
2: In Ops.factor(df$var3, 0) : < not meaningful for factors

任何意见,将不胜感激。谢谢你。

4

2 回答 2

4

您的问题是您使用cbindbefore data.frame,这会将您的三个变量强制转换为同一个类(必须是字符),导致它们在您制作 data.frame 时被强制考虑因素。

相反,只是做

df <- data.frame(var1, var2, var3)

运行相同的代码newVar,你应该得到:

  var1 var2 var3 newVar
1    A    G -0.1      2
2    T    A  3.0      4
3 <NA> <NA> -4.0     NA
4    G    A  5.0      3
5    C    G -3.0      2
于 2013-08-20T15:41:28.303 回答
1

您可以大大简化重新编码变量的方式。不要使用cbind已经在其他地方指出的那样,但是......您可以提供一个 2 列下标变量矩阵来对您的数据框进行子集化。所以我们可以这样做:

df <- data.frame( var1 , var2 , var3 )

#  Gives 1 if 'var3' is greater than 0 and 2 otherwise (the numbers of the columns you want!)
ind <- (! df$var3 > 0) + 1
#[1] 2 1 2 1 2

#  Get each row selecting either column 1 or two
df$newVar <- df[ cbind( 1:nrow(df) , ind ) ]
# var1 var2 var3 newVar
#1    A    G -0.1      G
#2    T    A  3.0      T
#3 <NA> <NA> -4.0   <NA>
#4    G    A  5.0      G
#5    C    G -3.0      G
于 2013-08-20T15:52:02.223 回答