R:如何检索数据框的列名 [英] R: How to retrieve a column name of a data frame
本文介绍了R:如何检索数据框的列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试根据单元格中的值提取数据帧的别名。我的数据是一系列数百个类别的,在单元格中有一个简单的二进制0或1,以指示我要在新df中使用的列名。
I am trying to extract the colnames of a data frame, based on the values in the cells. My data is a series of a couple hundred categories, with a simple binary 0 or 1 in the cells to indicate which column name I want in my new df.
为了说明我的观点:
year cat1 cat2 cat3 ... catN
2000 0 0 1 0
2001 1 0 0 0
2002 0 0 0 1
....
2018 0 1 0 0
我正在尝试获得df,例如:
I am trying to get a df like:
year category
2000 cat3
2001 cat1
2002 catN
....
2018 cat2
我的代码:
newdf <- as.data.frame(colnames(mydf)[which(mydf == "1", arr.ind = TRUE)[2]])
可惜,这只会返回一个类别名称!
But alas this only returns one category name!
任何帮助将不胜感激!
推荐答案
基本的R解决方案:
使用 sapply
查找其中的一个并获取名称。
Using sapply
to find which are the ones and get the names.
out <- data.frame(year = df1$year, category = names(sapply(df1[, -1], function(x) which(x == 1))))
out
year category
1 2000 cat1
2 2001 cat2
3 2002 cat3
4 2018 catN
数据:
df1 <- structure(list(year = c(2000L, 2001L, 2002L, 2018L), cat1 = c(0L,
1L, 0L, 0L), cat2 = c(0L, 0L, 0L, 1L), cat3 = c(1L, 0L, 0L, 0L
), catN = c(0L, 0L, 1L, 0L)), class = "data.frame", row.names = c(NA,
-4L))
这篇关于R:如何检索数据框的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文