R:在数据框中的值的基础上用行名替换列名

时间:2016-06-23 14:01:46

标签: r replace

我有一个数据框如下:

df <- data.frame(halloo = c(0.04,1,1,1), ciaoo = c(1,0.05,1, 1), bird=c(1,1,1,1))
row.names(df) <- c("hallo", "ciao", "else", "some")

在这里,我想检查一个单元格中的值是否低于/等于0.05,如果是这种情况,那么我想用相关单元格的行名称更改列名。

应用函数后,最终数据框应如下所示:

df.final <- data.frame(hallo = c(0.04,1,1,1), ciao = c(1,0.05,1, 1), bird=c(1,1,1,1))
row.names(df.final) <- c("hallo", "ciao", "else", "some")

实际上,虽然我试图找到一个解决方案但我不知道好的解决方案。有人有想法吗?

提前谢谢

2 个答案:

答案 0 :(得分:2)

我们可以将SELECT starts_at, (@row := @row + 1) + start_health_post_id as health_post_id FROM ( SELECT DATE_ADD(start_date, INTERVAL start_time MINUTE) AS starts_at FROM days CROSS JOIN times ) slots, (SELECT @row := -1)r ORDER BY starts_at; cross join Select practices.id as practice_id, providers.id as provider_id, practice_locations.id as practice_location_id from practices Inner Join providers on practices.health_post_id = providers.health_post_id Inner join practice_locations on practices.health_post_id = practice_locations.health_post_id; which一起使用,从逻辑矩阵(arr.ind=TRUE)中获取row/column索引矩阵。子集列向量('i2'),删除重复项('i3' - 因为符合条件的列中可能有多行),将'df'的列名称基于'i3'分配给'i3'的df <= 0.05

names

答案 1 :(得分:0)

我非常依赖订阅和功能来解决很多问题,所以这里有一个替代方案:

bool <- df <= 0.05
bool <- as.data.frame(bool)
x <- pryr::compose(unlist, lapply)(
    bool,
    function(x) row.names(bool[x, TRUE][1])
    # [1] to handle duplicates - just pull row name of first match
)
names(df)[1:length(x)] <- x