R factor 如何在R中添加新因子

R factor 如何在R中添加新因子,r-factor,R Factor,我有一个数据框: a <- c("",1,2,3,2,2,1,3,"") b <- c(1,2,3,4,5,3,8,2,8) a1 <- as.factor(a) f <- data.frame(x=a1,y=b) f a你不需要for循环,一个更快的方法是 a <- c("",1,2,3,2,2,1,3,"") > b <- c(1,2,3,4,5,3,8,2,8) > a1 <- as.factor(a) > f <- da

我有一个数据框:

a <- c("",1,2,3,2,2,1,3,"")
b <- c(1,2,3,4,5,3,8,2,8)
a1 <- as.factor(a)
f <- data.frame(x=a1,y=b)
f

a你不需要for循环,一个更快的方法是

a <- c("",1,2,3,2,2,1,3,"")
> b <- c(1,2,3,4,5,3,8,2,8)
> a1 <- as.factor(a)
> f <- data.frame(x=a1,y=b)
> 
> f$x <- ifelse(f$x=="",0,f$x)
> f$x
[1] 0 2 3 4 3 3 2 4 0
> f$x <- as.factor(f$x)
> str(f)
'data.frame':   9 obs. of  2 variables:
 $ x: Factor w/ 4 levels "0","2","3","4": 1 2 3 4 3 3 2 4 1
 $ y: num  1 2 3 4 5 3 8 2 8
aba1f
>f$x f$x
[1] 0 2 3 4 3 3 2 4 0
>f$x str(f)
“data.frame”:9个obs。共有2个变量:
$x:系数w/4级“0”、“2”、“3”、“4”:1 2 3 4 1
$y:num1 2 3 4 5 3 8 2 8

那么,您是想对一个更大的数据帧执行此操作吗?是的,这是一个大数据帧。我将因子更改为数字值,然后将0添加到零位,然后将其更改为因子,这是可行的,但您有更好的主意吗?(因子的来源是中文字符,我已将其更改为数字因子。)如果它工作,请upvotehow,我是这个网站的新用户。 Warning message: In if (is.na(f$x)) f$x 1 and only the first element will be used
for(i in 1:nrow(f)){
 if(is.na(f$x[i])){
     f$x[i] <- 0
 }
}
a <- c("",1,2,3,2,2,1,3,"")
> b <- c(1,2,3,4,5,3,8,2,8)
> a1 <- as.factor(a)
> f <- data.frame(x=a1,y=b)
> 
> f$x <- ifelse(f$x=="",0,f$x)
> f$x
[1] 0 2 3 4 3 3 2 4 0
> f$x <- as.factor(f$x)
> str(f)
'data.frame':   9 obs. of  2 variables:
 $ x: Factor w/ 4 levels "0","2","3","4": 1 2 3 4 3 3 2 4 1
 $ y: num  1 2 3 4 5 3 8 2 8