Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在R中翻转行和列_R - Fatal编程技术网

如何在R中翻转行和列

如何在R中翻转行和列,r,R,我目前有: Country.Name 1995 1996 1997 ... 2013 Country1 Country2 (numeric data) Country3 -这种格式使得很难绘制每个国家的数据图表并进行比较,因为标题列是各个年份 我想: Year Country1 Country2 Country3 1995 1996 1997 (numeric data) ... 2013 请参阅更多信息:假设您有

我目前有:

Country.Name   1995 1996 1997 ... 2013
Country1       
Country2        (numeric data)
Country3
-这种格式使得很难绘制每个国家的数据图表并进行比较,因为标题列是各个年份

我想:

Year  Country1   Country2   Country3
1995
1996        
1997           (numeric data)
...
2013

请参阅更多信息:

假设您有此数据框
df
,请参阅下面的数据

  Country.Name 1997 1998 1999 2000
1     Country1    1    1    1    1
2     Country2    2    4    7   10
3     Country3    4    2    1    5
首先,必须转置除第一列之外的所有数据帧。结果是我们需要转换为数据帧的矩阵。最后,我们将原始数据帧
df
的第一列指定为
df2
的列名

df2 <- data.frame(t(df[-1]))
colnames(df2) <- df[, 1]
数据:

     Country1 Country2 Country3
1997        1        2        4
1998        1        4        2
1999        1        7        1
2000        1       10        5
df <- structure(list(Country.Name = c("Country1", "Country2", "Country3"
), `1997` = c(1L, 2L, 4L), `1998` = c(1L, 4L, 2L), `1999` = c(1L, 
7L, 1L), `2000` = c(1L, 10L, 5L)), .Names = c("Country.Name", 
"1997", "1998", "1999", "2000"), class = "data.frame", row.names = c(NA, 
-3L))

df当我转换行和列时,新数据框的列名不会出现。R不允许我输入df_转置的$column_名称。我得到“$运算符对原子向量无效”你能用一些关于数据帧本身的信息更新你的问题吗?尝试
str(df_original)
给像我这样的初学者一个注释-如果在原始数据框中没有行号,则不需要代码的第二行
df <- structure(list(Country.Name = c("Country1", "Country2", "Country3"
), `1997` = c(1L, 2L, 4L), `1998` = c(1L, 4L, 2L), `1999` = c(1L, 
7L, 1L), `2000` = c(1L, 10L, 5L)), .Names = c("Country.Name", 
"1997", "1998", "1999", "2000"), class = "data.frame", row.names = c(NA, 
-3L))