-1

There is a data.frame, I print it with sapply:

df <- data.frame(name=c("alice","becka","james","jeffery","john"),  
                 sex=c("F","M","M","F","M"),  
                 age=c(13,13,12,13,12),  
                 height=c(56.5,65.3,57.3,62.5,69),  
                 weight=c(84,98,83,84,99.5),stringsAsFactors = FALSE)  
sapply(df,function(x){print(x)})  

 [1] "alice"   "becka"   "james"   "jeffery" "john"     
 [1] "F" "M" "M" "F" "M"  
 [1] 13 13 12 13 12  
 [1] 56.5 65.3 57.3 62.5 69.0  
 [1] 84.0 98.0 83.0 84.0 99.5  
      name      sex age  height weight  
 [1,] "alice"   "F" "13" "56.5" "84"    
 [2,] "becka"   "M" "13" "65.3" "98"    
 [3,] "james"   "M" "12" "57.3" "83"    
 [4,] "jeffery" "F" "13" "62.5" "84"    
 [5,] "john"    "M" "12" "69"   "99.5"  

Why is the output not as follows:

 [1] "alice"   "becka"   "james"   "jeffery" "john"     
 [1] "F" "M" "M" "F" "M"  
 [1] 13 13 12 13 12  
 [1] 56.5 65.3 57.3 62.5 69.0  
 [1] 84.0 98.0 83.0 84.0 99.5  

Why is there a data.frame at the end as part of whole output?

       name      sex age  height weight  
 [1,] "alice"   "F" "13" "56.5" "84"    
 [2,] "becka"   "M" "13" "65.3" "98"    
 [3,] "james"   "M" "12" "57.3" "83"    
 [4,] "jeffery" "F" "13" "62.5" "84"    
 [5,] "john"    "M" "12" "69"   "99.5"   
4

2 回答 2

3

print返回一个值,如果可以,sapply将其结果转换为 a 。matrix在这种情况下,它会打印您要求它打印的所有内容,然后返回其值,即字符矩阵。用于invisible隐藏第二步:

> invisible(sapply(df,function(x){print(x)}))
[1] "alice"   "becka"   "james"   "jeffery" "john"   
[1] "F" "M" "M" "F" "M"
[1] 13 13 12 13 12
[1] 56.5 65.3 57.3 62.5 69.0
[1] 84.0 98.0 83.0 84.0 99.5

可以通过示例找到 OP 所需的“可信或官方来源”:

> a <- print('bah')
> a
[1] "bah"

编辑:哎呀。的文档?print.default确实非常明确地说它返回了它的参数。(谢谢,@joran。)不过​​,我仍然希望“价值”部分再次提及它……

于 2013-11-06T01:22:43.963 回答
0

You should probably use skip = 13 to ignore the headers. Or use "China" as your starting line. You may be able to parse together a substitute set of column names afterward with pasting row9 to row 10 (or use month.abb). This will let you avoid complications of reading columns as factors.

x<- read.fwf(textConnection(ll[13:i2]), widths = c(20,-1,rep(c(7,-1),13)))

> str(x)
'data.frame':   39 obs. of  14 variables:
 $ V1 : Factor w/ 39 levels "All Other           ",..: 8 19 6 4 26 36 35 3 39 21 ...
 $ V2 : num  1268 1149 300 253 246 ...
 $ V3 : num  1279 1135 288 256 258 ...
 $ V4 : num  1276 1083 286 254 257 ...
于 2013-11-03T05:36:16.587 回答