r - Can I use the unlist function in a dataframe?
问题描述
I was working with a list containing the words from a text and the tags classifying them. I was supposed to restore an old letter, and to do this i needed to extract only the words in a vector, so instead of using sapply, i did this:
words <- unlist(data.frame(letter)[1,], use.names = FALSE)
It appeared to work, but the auxiliary professor said that doing this was a problem, since you can only use unlist in lists, so I fixed it, but in the end the results were the same.
PS: I know that using sapply is more efficient, i just didn't remember the function, I'm just curious to know if you can use unlist in other objects
解决方案
正如@Gregor 所说,data.frame
s 是列表。考虑以下示例:
df <- data.frame(Col1 = LETTERS[1:5], Col2 = 1:5, stringsAsFactors = FALSE)
is.list(df)
#[1] TRUE
因此,您可以使用lapply
on adata.frame
来执行按列操作:
lapply(df,paste0, collapse = "")
#$Col1
#[1] "ABCDE"
#$Col2
#[1] "12345"
但是,在对 a 进行子集化时,您必须小心,data.frame
因为根据您使用的方法,您可能无法获得列表。
df["Col2"]
# Col2
#1 1
#2 2
#3 3
#4 4
#5 5
is.list(df["Col2"])
#[1] TRUE
df[,"Col2"]
#[1] 1 2 3 4 5
is.list(df[,"Col2"])
#[1] FALSE
is.list(df[["Col2"]])
#[1] FALSE
is.list(df$Col2)
#[1] FALSE
is.list(subset(df,select = Col2))
#[1] TRUE
然而,据我所知,对整行进行子集化总是会返回一个列表。
df[1,]
# Col1 Col2
#1 A 1
is.list(df[1,])
#[1] TRUE
is.list(subset(df,1:5 == 1))
#[1] TRUE
我们可以使用该dput
函数查看单行底层结构的文本表示:
dput(df[1,])
#structure(list(Col1 = "A", Col2 = 1L), row.names = 1L, class = "data.frame")
正如我们所看到的,即使是单行也显然是一个列表。因此,我们可以合理unlist
地使用该行,就像我们对任何不是也是 a 的列表进行处理一样data.frame
。
unlist(df[1,], use.names = FALSE)
#[1] "A" "1"
unlist(list(Col1 = "A", Col2 = 1L), use.names = FALSE)
#[1] "A" "1"
推荐阅读
- heroku - 浏览器中的空白页面,控制台中出现意外令牌“<”
- javascript - 设置完全禁用/不可触碰的时间范围
- python - 为什么我在尝试使用 imapclient 时收到 TypeError?
- node.js - 如何将 google gmail api 身份验证从客户端共享到节点服务器
- geoserver - 地理服务器点样式 - 将所有记录中特定字段的值添加到标签中
- python-3.x - 当我单击“运行测试”时,为什么 pytest 会运行完整代码而不是测试?
- python - yfinance:选择一小时间隔时看不到一天中的时间
- webpack - Webpack 5 模块联合:使用身份验证访问远程模块
- reactjs - Grapqhql 数据在解构时是“未定义的”,尽管数据在那里
- r - 在R中将日期时间转换为三个字母的月份和年份