如何在R中矩阵转置后访问第一列

how to access first column after matrix transposed in R

我转置了我的数据,原始变量名现在位于标题为 row.names

的第一列中

我需要访问此专栏进行分析,但我不能。

以下数据示例:

    row.names CountryData YR1990 YR1991 YR1992
   1    3     AFG          1200   1160   1097
   2    4     AGO          320    417    397
   3    5     ALB          2794   2017   2269
   4    6     ARE          2216   1594   2341

 AFTER TRANSPOSED
    row.names AFG AGO ALB ARE
  1 YR1990 1200 320 2794 2216
  2 YR1991 1160 417 2071 1594
  3 YR1992 1097 397 2269 2315
  4 YR1993 1135 267 2685 858

  #Read in data
 >mydata=read.csv('CerialYield.csv',header=TRUE,dec=".",na.strings = c("NA",".."),  stringsAsFactors=FALSE)
 >mydata=mydata[1:233, 1:26]
 >CerialData=mydata[,7:26]
 >CountryData=mydata[,1]

#Transpose dataframe
>CerialCountryData=t(CerialData)
>colnames(CerialCountryData) <- CerialCountryData[1,]
>CerialCountryData <- CerialCountryData[2:nrow(CerialCountryData), ]

>CerialCountryData=as.data.frame(as.matrix(CerialCountryData))

structure(list(AFG = c(1200L, 1160L, 1097L, 1135L, 1140L, 1219L,  
1203L, 1349L, 1389L, 1286L), AGO = c(320L, 417L, 397L, 267L, 
298L, 402L, 653L, 567L, 701L, 620L), ALB = c(2794L, 2071L, 2269L, 
2685L, 2460L, 2841L, 2450L, 2833L, 2872L, 2798L)), .Names = c("AFG", 
"AGO", "ALB"), row.names = c("YR1990", "YR1991", "YR1992", "YR1993", 
"YR1994", "YR1995", "YR1996", "YR1997", "YR1998", "YR1999"), class = "data.frame")

你试过了吗:

>table_name$row.names

>table_name[,1]

因此,在您的 data.frame 中,这些是行名称而不是单独的列。为了访问这些名称,您需要 row.names 函数,即:

数据

structure(list(AFG = c(1200L, 1160L, 1097L, 1135L, 1140L, 1219L,  
1203L, 1349L, 1389L, 1286L), AGO = c(320L, 417L, 397L, 267L, 
298L, 402L, 653L, 567L, 701L, 620L), ALB = c(2794L, 2071L, 2269L, 
2685L, 2460L, 2841L, 2450L, 2833L, 2872L, 2798L)), .Names = c("AFG", 
"AGO", "ALB"), row.names = c("YR1990", "YR1991", "YR1992", "YR1993", 
"YR1994", "YR1995", "YR1996", "YR1997", "YR1998", "YR1999"), class = "data.frame")

解决方案

> row.names(df)
 [1] "YR1990" "YR1991" "YR1992" "YR1993" "YR1994" "YR1995" "YR1996" "YR1997" "YR1998" "YR1999"

您可以将其存储到变量中,然后将其用作向量。

希望对您有所帮助。