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
.
for (i in 1:length(day)) {
cat("Today is", day[i], "and it is a", weather[i], "day.\n")
cat(day[i], "is a", weather[i], "day\n")
}
# Today is Monday and it is a sunny day.
# Monday is a sunny day
# Today is Tuesday and it is a cloudy day.
# Tuesday is a cloudy day
# Today is Wednesday and it is a rainy day.
# Wednesday is a rainy day
# Today is Thursday and it is a stormy day.
# Thursday is a stormy day
# Today is Friday and it is a sunny day.
# Friday is a sunny day
# Today is Saturday and it is a cloudy day.
# Saturday is a cloudy day
# Today is Sunday and it is a rainy day.
# Sunday is a rainy day
This loops through all elements of your vector and it accesses each day and weather based on the index.
Day: "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday"
Index: 1 2 3 4 5 6 7
At the first iteration of the loop, i
is set to 1
, and day[i]
is "Monday"
. Likewise, weather[i]
is "sunny"
since "sunny"
is the first element in the weather
vector. That pattern is repeated over the whole vector.
So at the first iteration, the first sentence is
cat("Today is", "Monday", "and it is a", "sunny", "day.\n")
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments