R中的转置函数意外更改值

  • 本文关键字:意外 转置函数 r
  • 更新时间 :
  • 英文 :


我有以下我需要转置

的数据框架
                      A                 B
4                   4024               4796
5                   4130               4796
6                   4130               4796
7                   4130               4796
8                   4067               4687
9                   4067               4687

当我使用t(df(时,我会得到以下输出。

        4             5             6             7             8
A 1.988120e-320 2.040491e-320 2.040491e-320 2.040491e-320 2.009365e-320
B 2.369539e-320 2.369539e-320 2.369539e-320 2.369539e-320 2.315686e-320
        9
A 2.009365e-320
B 2.315686e-320

为什么值更改?

一个选项是 gather to'a','b'列以从行名创建列,然后 spread到'wide'格式并更改'''''a','b'列对'long'格式。钥匙列到行名

library(tidyverse)
rownames_to_column(df1, 'rn') %>% 
  gather(key, val, A:B) %>% 
  spread(rn, val) %>%
  column_to_rownames('key')
#    4    5    6    7    8    9
#A 4024 4130 4130 4130 4067 4067
#B 4796 4796 4796 4796 4687 4687

值更改的原因是因为列是factor,并且通过转移,将其转换为matrix,其中factor值更改为整数编码值

一个选项是首先将列转换为character,然后将列转换为integer(如果需要(,然后进行transpose

t(sapply(df1, function(x) as.integer(as.character(x))))

数据

df1 <- structure(list(A = c(4024L, 4130L, 4130L, 4130L, 4067L, 4067L
), B = c(4796L, 4796L, 4796L, 4796L, 4687L, 4687L)), 
 class = "data.frame", row.names = c("4",
 "5", "6", "7", "8", "9"))

最新更新