18

我有一个包含数据的文件c("A","T","B","F")

当我使用:

read.csv(myfile,header=F,stringsAsFactors=F)

R将字符解释TTRUEFFALSE

我做错什么了吗?

4

3 回答 3

23

如果你所有的列都是字符,那么试试这个:

# replace text = . with your filename
read.csv(text="A,B,T,T", header=FALSE, stringsAsFactors=FALSE, 
            colClasses = c("character"))

否则,您必须将每列的类型传递colClasses为:colClasses = c("numeric", "numeric", "character", ...)

于 2013-04-25T12:19:50.337 回答
1

我遇到了类似的问题,这是解决方案:

#dummy data
df <- read.csv(text="
A,B,T,T,F
T,T,F,T,text1
A,T,NA,F,T",
               header=FALSE, stringsAsFactors=FALSE)
#data
df
#   V1 V2    V3    V4    V5
# 1  A  B  TRUE  TRUE     F
# 2  T  T FALSE  TRUE text1
# 3  A  T    NA FALSE     T

#convert logical columns to single letters
df[,sapply(df,class) == "logical"] <-
  sapply(df[,sapply(df,class) == "logical"],
         function(i) substr(as.character(i),1,1))

#result
df
#   V1 V2   V3 V4    V5
# 1  A  B    T  T     F
# 2  T  T    F  T text1
# 3  A  T <NA>  F     T
于 2015-03-05T10:47:41.067 回答
1

如果您不想更改所有列的类,revalue 也可以,但更适合对一列进行简单更改。

df$V3 <- as.factor(revalue(df$V3, c("TRUE" = "T", "FALSE" = "F")))
于 2017-10-10T23:59:38.053 回答