如何在此数据库中正确使用R中的read.table?

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

我正在尝试使用R中的read.table(file="clipboard")读取此虚拟数据库:

             Aspecto   Sexo      Ranking
1             Imagen   Hombre    7.50
2      Mantenimiento   Hombre    7.18
3               Otro   Hombre    7.05
4  Espacios de venta   Hombre    6.91
5         Vigilancia   Hombre    6.36
6             Tiempo   Hombre    6.51
7    Espacios libres   Hombre    6.40
8             Imagen   Mujer     7.21
9      Mantenimiento   Mujer     7.30
10              Otro   Mujer     6.90
11 Espacios de venta   Mujer     7.02
12        Vigilancia   Mujer     6.53
13            Tiempo   Mujer     6.40
14   Espacios libres   Mujer     5.78

此代码似乎有效:

pw <- read.table(file="clipboard", dec=".", sep=",", header=TRUE)

但是结构显然是我不想要的:

str(pw)
'data.frame':   14 obs. of  1 variable:
 $ Aspecto...Sexo......Ranking: Factor w/ 14 levels "1  

我已经尝试了很多事情,包括fill=TRUE和其他参数,但我无法达到我的期望。例如:

pw <- read.table(file="clipboard", dec=".", sep="", header=TRUE)
Error in read.table(file = "clipboard", dec = ".", sep = "", header = TRUE) : 
  more columns than column names

任何建议将不胜感激。

r dataframe clipboard read.table
1个回答
0
投票

您可以使用read.fwf,因为这些列具有固定的宽度,并且您在字符串两边没有引号。并且由于第一行只有3个名称,因此我们将其跳过,但稍后使用scan读取它们。

clipboard <- read.fwf("clipboard.txt", widths=c(2,18,9,8), skip=1, as.is=TRUE) 
# or row.names=1 to ignore the first un-named column

colnames(clipboard)[2:4] = scan("clipboard.txt", what=rep("character", 3), nlines=1)

str(clipboard)

'data.frame':   14 obs. of  4 variables:
 $ V1     : num  1 2 3 4 5 6 7 8 9 10 ...
 $ Aspecto: chr  "            Imagen" "     Mantenimiento" "              Otro" " Espacios de venta" ...
 $ Sexo   : chr  "   Hombre" "   Hombre" "   Hombre" "   Hombre" ...
 $ Ranking: num  7.5 7.18 7.05 6.91 6.36 6.51 6.4 7.21 7.3 6.9 ...
© www.soinside.com 2019 - 2024. All rights reserved.