【发布时间】:2017-05-11 15:51:51
【问题描述】:
我正在尝试使用 R 以自定义方式打印一些数据,以便在单独的程序中使用。它一直试图留下我的号码,我无法让它停下来。我无法找到 ?format、?print、?cat、?etc 中的任何内容。完全解决我的问题。此外,搜索固定宽度或可变宽度会导致人们希望解决一些不同的问题(并且大多数人希望更改填充样式——而不是删除它)。
进行以下数据设置:
> df.play <- data.frame(name = c('a','b','c'), value = c(1,11,111))
> df.play
name value
1 a 1
2 b 11
3 c 111
这是我想要的输出
#Goal
> for (j in seq(nrow(df.play))) {cat(as.character(df.play[j,1]),'.',df.play[j,2],'\n',sep='')}
a.1
b.11
c.111
如何在不显式循环的情况下获得这种输出格式(最好避免使用外部库)?
#Naive Attempt 1
# Why does it left pad the second "column"?
# How do I get it to stop?
# Why does cat even parse it as a column to begin with?
junk<-apply(df.play,1,function(x) cat(x[1],'.',x[2],'\n',sep=''))
a. 1
b. 11
c.111
#Naive Attempt 2
# Perhaps this will help provide some insight.
# The number is a string before it gets to cat. Why?
t<-apply(df.play,1,function(x) cat(x[1],'.',sprintf('%d',x[2]),'\n',sep=''))
Error in sprintf("%d", x[2]) :
invalid format '%d'; use format %s for character objects
【问题讨论】: