I have a sentence and I printed it in two lines:
cat("Today is Monday and it is sunny.\nMonday is a sunny day\n")
and I have two lists:
day<-c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
weather<-c("sunny", "cloudy", "rainy", "stormy","sunny", "cloudy", "rainy")
I am trying to produce a text file which would contain the string variable above but with every day and weather variable in the lists.
So I would have:
Today is Monday and it is sunny.
Monday is a sunny day
Today is Tuesday and it is cloudy.
Tuesday is a cloudy day
Today is Wednesday and it is rainy.
Wednesdady is a rainy day
.... and so on.
I am wondering if this is possible in R. I am a relatively new beginner of R so any explanation would be much appreciated!!
You could construct a simple loop and print using
cat
.This loops through all elements of your vector and it accesses each day and weather based on the index.
At the first iteration of the loop,
i
is set to1
, andday[i]
is"Monday"
. Likewise,weather[i]
is"sunny"
since"sunny"
is the first element in theweather
vector. That pattern is repeated over the whole vector.So at the first iteration, the first sentence is
By default,
cat
separates consecutive values with a space. So this prints exactly the sentence we're looking for. The same is done for the second sentence.