如何在使用read_csv读取csv文件时跳过第二行,同时保留第一行作为列名?

3

Qualtrics生成的CSV文件第一行是变量名,第二行是变量标签。我想使用read_csv()函数读取数据,同时将第一行读入作为列名,并跳过下一行的变量标签。以下是我的失败尝试:

library(readr)
mydata <- read_csv("qualtrics_data.csv", col_names = TRUE, skip = 2) # this would actually skip both the names and label rows. 

1
这个帮助我解决了一个类似的问题:https://dev59.com/JWAg5IYBdhLWcg3wfa96 - GlennFriesen
2个回答

9
你可以两次读取数据,第一次读取名称,第二次读取数据。
library(readr)
library(dplyr)

csv_file <- "mpg,cyl,disp,hp,drat,wt
mpg,cyl,disp,hp,drat,wt
21.0,6,160,110,3.90,2.875
22.8,4,108,93,3.85,2.320
21.4,6,258,110,3.08,3.215
18.7,8,360,175,3.15,3.440
18.1,6,225,105,2.76,3.460"


df_names <- read_csv(csv_file, n_max = 0) %>% names()

df_names
#> [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"

df <- read_csv(csv_file, col_names = df_names, skip = 2)

df

#> # A tibble: 5 x 6
#>     mpg   cyl  disp    hp  drat    wt
#>   <dbl> <int> <int> <int> <dbl> <dbl>
#> 1  21.0     6   160   110  3.90 2.875
#> 2  22.8     4   108    93  3.85 2.320
#> 3  21.4     6   258   110  3.08 3.215
#> 4  18.7     8   360   175  3.15 3.440
#> 5  18.1     6   225   105  2.76 3.460

0

使用read.csv

df <- read.csv("example.csv")
df <- df[-1,] # -1 removes the first row, you can change to -2 to remove 2nd row...etc

1
由于第二行包含标签,这样做会导致所有列被解析为字符变量。 - austensen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接