将空格分隔的数据集加载到 R 中,而不删除字符串之间的空格

问题描述 投票:0回答:1

我有一个大的 csv 文件,其中一行的所有值都在一个单元格中,并用空格分隔。该数据是数值和字符串的混合。当我加载数据时,它会将单个变量的字符串拆分为多个列。

数据结构示例:

  • 调查“地点编号”“代码”“物种名称”“长度”“性别”“年龄”“站点”“经度”“纬度”“日期”“重量”
    1 “T 19/11” 45 “MMM” “Gadus Morhua” 80 “U” NA “F5” -7.979 50.837 2011-11-14 4
    2 “T 20/14” 20 “MNE” “白鹤” 75 “U” “0” 1 -2.501 50.216 2014-10-02 3*

其中每一行都是一行(单个单元格中每行的所有数据)

我需要的数据如下:

调查 站点编号 物种名称 长度 年龄 车站 经度 纬度 日期 重量
T 19/11 45 加杜斯莫华 80 1 F5 -7.979 50.837 2011-11-14 4
20/14 时间 20 跨国公司 白鹤 75 0 1 -2.501 50.216 2014-10-02 3

干杯

r csv dataset delimiter data-wrangling
1个回答
0
投票

sep=' '
中使用
read.table

r <- read.table('foo.csv', sep=' ')
r
#    Survey SiteNo CODE     Species_name Length Sex Age Station lonitude latitude       Date Weight
# 1 T 19/11     45  MMM     Gadus Morhua     80   U  NA      F5   -7.979   50.837 2011-11-14      4
# 2 T 20/14     20  MNE Homarus Gammarus     75   U   0       1   -2.501   50.216 2014-10-02      3

哪里

str(r)
# 'data.frame': 2 obs. of  12 variables:
#  $ Survey      : chr  "T 19/11" "T 20/14"
#  $ SiteNo      : int  45 20
#  $ CODE        : chr  "MMM" "MNE"
#  $ Species_name: chr  "Gadus Morhua" "Homarus Gammarus"
#  $ Length      : int  80 75
#  $ Sex         : chr  "U" "U"
#  $ Age         : int  NA 0
#  $ Station     : chr  "F5" "1"
#  $ lonitude    : num  -7.98 -2.5
#  $ latitude    : num  50.8 50.2
#  $ Date        : chr  "2011-11-14" "2014-10-02"
#  $ Weight      : num  4 3

.csv 内容

Survey "SiteNo" "CODE" "Species_name" "Length" "Sex" "Age" "Station" "lonitude" "latitude" "Date" "Weight"  
1 "T 19/11" 45 "MMM" "Gadus Morhua" 80 "U" NA "F5" -7.979 50.837 2011-11-14 4   
2 "T 20/14" 20 "MNE" "Homarus Gammarus" 75 "U" "0" 1 -2.501 50.216 2014-10-02 3
© www.soinside.com 2019 - 2024. All rights reserved.