从.csv文件加载数据,然后将其保存在R中的字典中

从.csv文件加载数据,然后将其保存在R中的字典中,r,dictionary,data-structures,import-from-csv,R,Dictionary,Data Structures,Import From Csv,我需要从.csv文件加载数据,然后将其保存在R中的词典中 需要从.csv文件加载上万行数据输入 数据格式: country,region,value 1 , north , 101 1 , north , 219 2 , south , 308 2 , south , 862 ... , ... , ... 我的预期结果可以保存在R的数据结构中: country , region, list of values

我需要从.csv文件加载数据,然后将其保存在R中的词典中

需要从.csv文件加载上万行数据输入

数据格式:

  country,region,value
     1  ,  north , 101
     1  ,  north , 219
     2  ,  south , 308
     2  ,  south , 862
   ... , ...     , ...
我的预期结果可以保存在R的数据结构中:

    country , region, list of values
     1  north     101 , 219 
     2  south     308 , 862 
这样我就可以得到与同一国家和地区相关的值

每行可能有不同的国家和地区

我需要将同一国家和地区的价值保存在一起


任何帮助都将不胜感激

对于输入数据,您到底愿意假设什么,也不清楚期望的输出是什么。或许

tmp <- read.csv(text="country,region,value
     1  ,  north , 101
     1  ,  north , 219
     2  ,  south , 308
     2  ,  south , 862")

dups <- duplicated(tmp[1:2])
dat <- data.frame(tmp[!dups, 1:2], value = paste(tmp[!dups, 3], tmp[dups, 3], sep = " , "))
dat
##   country   region     value
## 1       1   north  101 , 219
## 3       2   south  308 , 862

tmp如果我是你,我会坚持以“长”的形式保存你的数据。但是,如果确实希望以这种方式“聚合”数据,可以查看
aggregate
函数:

选项1:以列表形式存储在列中的值。很有趣,但以后会有麻烦的

aggregate(value ~ country + region, tmp, I, simplify=FALSE)
#   country   region    value
# 1       1   north  101, 219
# 2       2   south  308, 862
str(.Last.value)
# 'data.frame':  2 obs. of  3 variables:
#  $ country: num  1 2
#  $ region : Factor w/ 2 levels "  north ","  south ": 1 2
#  $ value  :List of 2
#   ..$ 1:Class 'AsIs'  int [1:2] 101 219
#   ..$ 3:Class 'AsIs'  int [1:2] 308 862
选项2:存储为单个逗号分隔字符向量列的值。以后要处理的麻烦更少,但可能需要进一步处理(再次拆分)才能发挥更大的作用

aggregate(value ~ country + region, tmp, paste, collapse = ",")
#   country   region   value
# 1       1   north  101,219
# 2       2   south  308,862
str(.Last.value)
# 'data.frame': 2 obs. of  3 variables:
#  $ country: num  1 2
#  $ region : Factor w/ 2 levels "  north ","  south ": 1 2
#  $ value  : chr  "101,219" "308,862"

请你需要给出更好的例子,提出你的问题clear@Chinmay帕蒂尔,我已经更新了操作。谢谢!我认为的答案正是你想要的,但应该注意的是,R中没有字典类型。@Ista使用
数据。框架
正是你想要的,但如果我读对了你的问题,你需要执行
write.csv()
调用创建
dat
,将
dat
保存到数据文件。@hrbrmstr,我需要从文件中加载数据,然后对它们进行一些分析。我已经更新了操作。谢谢!