【问题标题】:R: Create a new data frame from an existing data frame to study changes in one variable (column)R:从现有数据框创建新数据框以研究一个变量(列)的变化
【发布时间】:2021-03-22 01:21:42
【问题描述】:

例如,假设我有一个如下所示的数据框:

1   0.00038 0.75053 0.50    35  6000    0.75346
2   0.00038 0.75053 0.50    35  6050    0.72079
3   0.00038 0.75053 0.50    35  6100    0.69229
4   0.00038 0.75053 0.50    35  6150    0.66689
5   0.00038 0.75053 0.50    35  6200    0.64382
6   0.00038 0.75053 0.50    35  6250    0.62269
7   0.00038 0.75053 0.50    35  6300    0.60313
# and so on

在这个数据框中,我想知道第 6 列中的值何时等于 6550、第 2 列 = 0.00030、第 3 列 = 0.75000 和第 4 列 = 0.50(也许研究当列中的值时因变量如何变化5 个变化)。如果是这样,我想使用满足此条件的所有行创建一个新数据框。有什么建议吗?

【问题讨论】:

    标签: r


    【解决方案1】:

    这可能对你有用。

    • 第一pivot_longer
    • 然后使用case_when 检查条件
    • 然后pivot_wider 获取新的数据帧
    library(tidyverse)
    
    # your data last line added to met condition
    df <- tribble(
      ~col1, ~col2, ~col3, ~col4, ~col5, ~col6,
    0.00038, 0.75053, 0.50, 35, 6000, 0.75346, 
    0.00038, 0.75053, 0.50, 35, 6050, 0.72079, 
    0.00038, 0.75053, 0.50, 35, 6100, 0.69229, 
    0.00038, 0.75053, 0.50, 35, 6150, 0.66689, 
    0.00038, 0.75053, 0.50, 35, 6200, 0.64382, 
    0.00038, 0.75053, 0.50, 35, 6250, 0.62269, 
    0.00038, 0.75053, 0.50, 35, 6300, 0.60313,
    0.00038, 0.00030, 0.75000, 0.50, 6300, 6550) # added to fullfill true
    
    # your conditions
    # column 6 equals 6550, 
    # column 2 = 0.00030,
    # column 3 = 0.75000, 
    # and column 4 = 0.50 
    
    df1 <- df %>% 
        pivot_longer(cols = starts_with("col"), names_to = "Cols", values_to= "Values") %>% 
        mutate(check = case_when(Cols == "col6" & Values == 6550 ~ "col6TRUE",
                                 Cols == "col2" & Values == 0.00030 ~ "col2TRUE",
                                 Cols == "col3" & Values == 0.75000 ~ "col3TRUE",
                                 Cols == "col4" & Values == 0.50 ~ "col4TRUE")
        ) %>% 
        filter(!is.na(check)) %>% 
        pivot_wider(names_from = Cols, values_from = Values)
    
    

    【讨论】:

    • 嗨,我收到了错误Error: cols must select at least one column. Run rlang::last_error() to see where the error occurred
    猜你喜欢
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多