ihm*_*ihm 128 warnings r r-faq
我不明白为什么我收到这条警告信息.
> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3))
> fixed[1, ] <- c("lunch", 100)
Warning message:
In `[<-.factor`(`*tmp*`, iseq, value = "lunch") :
invalid factor level, NA generated
> fixed
Type Amount
1 <NA> 100
2 0
3 0
Run Code Online (Sandbox Code Playgroud)
Dav*_*vid 198
警告消息是因为您的"类型"变量是一个因素而"午餐"不是定义的级别.stringsAsFactors = FALSE
在创建数据框时使用标志强制"类型"为字符.
> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3))
> str(fixed)
'data.frame': 3 obs. of 2 variables:
$ Type : Factor w/ 1 level "": NA 1 1
$ Amount: chr "100" "0" "0"
>
> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3),stringsAsFactors=FALSE)
> fixed[1, ] <- c("lunch", 100)
> str(fixed)
'data.frame': 3 obs. of 2 variables:
$ Type : chr "lunch" "" ""
$ Amount: chr "100" "0" "0"
Run Code Online (Sandbox Code Playgroud)
Chi*_*rag 41
如果您直接从CSV文件中阅读,请执行此操作.
myDataFrame <- read.csv("path/to/file.csv", header = TRUE, stringsAsFactors = FALSE)
Run Code Online (Sandbox Code Playgroud)
tot*_*ico 22
这是一种灵活的方法,它可以在所有情况下使用,特别是:
dataframe
已经从先前施加的操作(例如获得不立即打开一个文件,或者创建一个新的数据帧).首先,使用函数对字符串进行非因式分解as.character
,然后使用(或简单)函数重新分解:as.factor
factor
fixed <- data.frame("Type" = character(3), "Amount" = numeric(3))
# Un-factorize (as.numeric can be use for numeric values)
# (as.vector can be use for objects - not tested)
fixed$Type <- as.character(fixed$Type)
fixed[1, ] <- c("lunch", 100)
# Re-factorize with the as.factor function or simple factor(fixed$Type)
fixed$Type <- as.factor(fixed$Type)
Run Code Online (Sandbox Code Playgroud)
小智 6
解决此问题的最简单方法是为列添加新因子.使用级别功能确定您拥有的因子数量,然后添加新因子.
> levels(data$Fireplace.Qu)
[1] "Ex" "Fa" "Gd" "Po" "TA"
> levels(data$Fireplace.Qu) = c("Ex", "Fa", "Gd", "Po", "TA", "None")
[1] "Ex" "Fa" "Gd" "Po" " TA" "None"
Run Code Online (Sandbox Code Playgroud)