math
math

Reputation: 2022

Printing strings and arguments of functions in R

I've two questions about R. There are quite simple, but unfortunately I don't find something in the web.

  1. Is it possible to write a function in R, fun1<-function(place) such that the argument "place" is the filename which I want to import in my case, i.e.

    fun1 <- function(place)
    data <- read.table(/home/place.csv, header=TRUE, sep=",")
    
  2. Suppose the variable c is assigned to a number for example age of a person. Then I want to print out a string like this: "hello my age is c". How do you do this in R?

Upvotes: 2

Views: 4082

Answers (2)

Erik Shilts
Erik Shilts

Reputation: 4509

  1. You can use sprintf, paste0, etc for the first part.

    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 isn't needed since paste is vectorized.

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

Upvotes: 7

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

I'm not sure what you're trying to achieve in the first part of your question. Can you explain that further?

For the second part, what about something like this:

> 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"

Upvotes: 2

Related Questions