为什么 R 将我的用户名更改为行号?有办法修复我的代码吗?

问题描述 投票:0回答:1
View(Offense.Passing.Stats) #<--- NOTE: This is a filtered and binded variable through dyplr::bind_rows

                 | Touchdowns | Interceptions |
                 | <int>      | <int>         |
                 | --------   | --------      |
MonsterWyatt...1 | 3          | NA            |
rvmo...2         | 3          | NA            |
MonsterWyatt...3 | NA         | 4             |
rvmo...4         | NA         | 4             | 


library(tidyverse)

Offense.Passing.Stats = Offense.Passing.Stats %>%

 bind_rows() %>%
 gather(statistic, value, "Touchdowns":"Passing.Yards") %>%
 na.omit()

 View(Offense.Passing.Stats)

      |    statistic  | value    |
      |      <chr>    | <int>    |
1     |    Touchdowns |    3     |
2     |    Touchdowns |    3     |
18    | Interceptions |    4     |
19    | Interceptions |    4     |

^ 如何通过第二个代码获取“MonsterWyatt”和“rvmo”?而不是数据框本身的行号

我试图回去看看是否可以采取完全不同的方法来过滤掉我的变量,但它不起作用,所以这是让变量像这样弹出并实际分离出数字的唯一方法,因为如果我以其他方式执行它,它实际上不会携带用户名。

任何帮助将不胜感激,我确信这也只是一个小修复

我对 R 非常陌生,不知道如何修复代码中的这个小问题。

r dataframe dplyr tidyverse
1个回答
0
投票

有两件事你必须知道:

  1. tibbles 不接受行名!
  2. 数据帧确实接受,但值必须是唯一的,因此 MonsterWyatt-rvmo-MonsterWyatt-rvmo 是不可能的

这是解决此问题的一种方法:

library(tidyverse)

Offense.Passing.Stats %>% 
  rownames_to_column("my_rownames") %>% 
  mutate(my_rownames = str_extract(my_rownames, "^\\w+")) %>% 
  bind_rows() %>%
  pivot_longer(-my_rownames, 
               names_to = "Touchdowns", 
               values_to = "Passing.Yeard",
               values_drop_na = TRUE) 
 my_rownames  Touchdowns    Passing.Yeard
  <chr>        <chr>                 <int>
1 MonsterWyatt Touchdowns                3
2 rvmo         Touchdowns                3
3 MonsterWyatt Interceptions             4
4 rvmo         Interceptions             4
© www.soinside.com 2019 - 2024. All rights reserved.