我在从data.frame获取所需的输出时遇到问题。数据的结构如下:
head(test)
A T L B E X D
4 no no no yes no no yes
7 no no no no no no no
11 no no no no no no no
12 no no no yes no no yes
17 no no no no no no no
27 no no no no no no no
我得到的输出:
test[1,]
A T L B E X D
4 no no no yes no no yes
我想要的输出:
[1] "no" "no" "no" "yes" "no" "no" "yes"
或者简单地说,我想要的输出是一个向量,其中每个元素都是df
中该列的字符串值。我可以进行for循环或类似的愚蠢操作,但我相信应该缺少一种更简单的方法。
我尝试过:
as.character(test[1,])
[1] "1" "1" "1" "2" "1" "1" "2"
不确定我在这里想念什么吗?
答案 0 :(得分:1)
使用unlist
,然后使用as.character
as.character(unlist(test[1, ]))
#[1] "no" "no" "no" "yes" "no" "no" "yes"
test[1, ]
仍然是数据帧,并且在数据帧上应用as.character
无效。我们使用unlist
将数据帧转换为矢量,然后使用as.character
将其转换为字符。
数据
test <- structure(list(A = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "no", class = "factor"),
T = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "no", class = "factor"),
L = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "no", class = "factor"),
B = structure(c(2L, 1L, 1L, 2L, 1L, 1L), .Label = c("no",
"yes"), class = "factor"), E = structure(c(1L, 1L, 1L, 1L,
1L, 1L), .Label = "no", class = "factor"), X = structure(c(1L,
1L, 1L, 1L, 1L, 1L), .Label = "no", class = "factor"), D = structure(c(2L,
1L, 1L, 2L, 1L, 1L), .Label = c("no", "yes"), class = "factor")),
class = "data.frame", row.names = c("4", "7", "11", "12", "17", "27"))