如何逐行打印data.frame值

时间:2018-10-23 10:10:31

标签: r

我想将data.frame转换为以下格式:

(col1row1Value, col2row1Value, ... colNrow1Value),
(col1row2Value, col2row2Value, ... colNrow2Value),
...
(col1rowNValue, col2rowNValue, ... colNrowNValue)  

这是我的肮脏解决方案:

convert <- function(df) {
  df <- data.frame(lapply(df, as.character), stringsAsFactors = F)

  result <- ""
  for(i in 1:nrow(df)) {
    x <- paste(df[i, ], collapse = ", ")
    result <- paste0(result, "(", x, "),\n" )
  }
  result <- substr(result, 1, nchar(result) - 1)
  result
}

测试:

cat(convert(iris[1:5,]))

有什么想法可以改善它吗?

3 个答案:

答案 0 :(得分:1)

有帮助吗?

iris$new<- apply(iris, 1,paste0, collapse = ",")
print(apply(iris[,6, drop= F], 2, function(f) paste0("(", f, ")", collapse= ",")))

答案 1 :(得分:0)

也许带有tidyverse:

convert <- function (df) 
  df %>% mutate_if(Negate(is.character),as.character) %>%
    mutate(id=row_number()) %>%
    gather(k,v,-id) %>%
    group_by(id) %>% summarise(z=paste0("(",paste(v,collapse=", "),")")) %>%
    pull(z) %>% paste(collapse=",\n")

cat(convert(iris[1:5,]))
#(5.1, 3.5, 1.4, 0.2, setosa),
#(4.9, 3, 1.4, 0.2, setosa),
#(4.7, 3.2, 1.3, 0.2, setosa),
#(4.6, 3.1, 1.5, 0.2, setosa),
#(5, 3.6, 1.4, 0.2, setosa)

答案 2 :(得分:0)

这是另一种实现方法(如果需要,可以将其包装在函数中)。

itest <- iris[1:5,] %>%
  mutate(Species = as.character(Species))

ct <- 1:nrow(itest)

tbl <- tibble()

for (i in ct) {

  r <- itest[i,]
  newct <- 1:ncol(r)

  vals <- character()

  for (i in newct) {

    new_val <- r[,i]

    vals <- c(vals,new_val)
  }

  new_tbl <- tibble(stringrow = paste(vals,collapse=', '))

  tbl <- bind_rows(tbl,new_tbl)

}

结果:

# A tibble: 5 x 1
  stringrow                 
  <chr>                     
1 5.1, 3.5, 1.4, 0.2, setosa
2 4.9, 3, 1.4, 0.2, setosa  
3 4.7, 3.2, 1.3, 0.2, setosa
4 4.6, 3.1, 1.5, 0.2, setosa
5 5, 3.6, 1.4, 0.2, setosa