如何从数据框中的一行中获取特定值?

问题描述 投票:0回答:2

我正在使用类树和“rpart”库进行预测,当我进行“预测”时,我会得到一个包含概率及其测试数据可以采用的值/类别的表,我想获取该值/类别中的最高概率。例如(一旦预测完成),我得到的表是:

enter image description here

我想要这张桌子:

enter image description here

r dataframe
2个回答
1
投票

实现所需输出的一种方法可能是:

  1. 确定向量中的值
    pattern
  2. 跨相关列进行变异并使用
    str_detect
    检查值是否在此列中 -> 如果为 true,请使用
    cur_column()
    放置 新列中的列名称。 用
    .names
    unite
    做一些技巧并且 最后选择。
library(dplyr)
library(tidyr)
library(stringr)

pattern <- c("0.85|0.5|0.6|0.8")

df %>% 
  mutate(across(starts_with("cat"), ~case_when(str_detect(., pattern) ~ cur_column()), .names = 'new_{col}')) %>%
  unite(New_Col, starts_with('new'), na.rm = TRUE, sep = ' ') %>% 
  select(index, pred_category = New_Col)
  index pred_category
  <dbl> <chr>        
1     1 cat2         
2     2 cat1         
3     3 cat3         
4     4 cat3  

0
投票

您没有发布您的数据,所以我只是将其放入 .csv 中并从 C: 驱动器上的 R 文件夹中访问它。

可能是一种更简单的方法,但这是我在可能有多种不同类型(按列或行)想要排序时使用的方法。如果您是 R 新手并且尚未安装 data.table 或 dplyr,则需要在控制台中输入第二部分。

我保留了这些值,但如果您不需要它们,可以用最后一行来修复它们。

setwd("C:/R")

library(data.table)
library(dplyr)

Table <- read.csv("Table1.csv", check.names = FALSE, fileEncoding = 'UTF-8-BOM')

#Making the data long form makes it much easier to sort as your data gets more complex.
LongForm <- melt(setDT(Table), id.vars = c("index"), variable.name = "Category")

Table1 <- as.data.table(LongForm)

#This gets you what you want.
highest <- Table1 %>% group_by(index) %>% top_n(1, value)

#Then just sort it how you wanted it to look
Table2 <- highest[order(highest$index, decreasing = FALSE), ]

View(Table2)

如果您没有合适的套餐

install.packages("data.table")

install.packages("dplyr")

去掉数字

Table3 <- Table2[,1:2]
© www.soinside.com 2019 - 2024. All rights reserved.