在R中打印字符串和函数参数

时间:2012-04-24 18:36:24

标签: r

我有两个关于R的问题。很简单,但不幸的是我在网上找不到任何东西。

  1. 是否可以在R,fun1<-function(place)中编写一个函数,使得参数“place”是我想在我的情况下导入的文件名,即

    fun1 <- function(place)
    data <- read.table(/home/place.csv, header=TRUE, sep=",")
    
  2. 假设变量c被分配给一个数字,例如一个人的年龄。然后我想要打印出这样的字符串:"hello my age is c"。你是怎么用R做的?

2 个答案:

答案 0 :(得分:7)

  1. 您可以在第一部分使用sprintfpaste0等。

    fun1 <- function(place) read.table(sprintf('/home/%s.csv', place), 
                                       header=TRUE, sep=",")
    
    fun2 <- function(place) read.table(paste0('/home/', place, '.csv'), 
                                       header=TRUE, sep=",") 
    # paste0 only works in recent versions of R
    
    fun3 <- function(place) read.table(paste('/home/', place, '.csv', sep=''),
                                       header=TRUE, sep=",")
    
    # Now call the functions
    fun1('test.csv')
    fun2('test.csv')
    fun3('test.csv')
    
  2. sapply不需要paste被矢量化。

    ages <- 10:20
    paste('Hello my name is', ages)
    

答案 1 :(得分:2)

我不确定你在问题的第一部分想要实现的目标。你能进一步解释一下吗?

对于第二部分,这样的事情是什么:

> ages = c(40, 23, 13, 42, 53)
> sapply(ages, function(x) paste("Hello, my age is", x))
[1] "Hello, my age is 40" "Hello, my age is 23" "Hello, my age is 13" "Hello, my age is 42"
[5] "Hello, my age is 53"