R not printing the right thing in loop
Okay, you are trying to construct a variable name using paste and then do a table. You are simply passing the name of the variable to table, not the variable object itself. For this sort of approach you want to use get()
for (i in 1:4) {
with(get(paste0("group", i), table(BMI_obese, A1.1))
}
#example saving as a list (using lapply rather than for loop)
group1 <- data.frame(x=LETTERS[1:10], y=(1:10)[sample(10, replace=TRUE)])
group2 <- data.frame(x=LETTERS[1:10], y=(1:10)[sample(10, replace=TRUE)])
result <- lapply(1:2, function(i) with(get(paste0("group", i)), table(x, y)))
#look at first six rows of each:
head(result[[1]])
head(result[[2]])
#example illustrating fetching objects from a string name
data(mtcars)
head(with(get("mtcars"), table(disp, cyl)))
head(with(get("mtcars"), table(disp, "cyl")))
#Error in table(disp, "cyl") : all arguments must have the same length
head(with(get("mtcars"), table(disp, get("cyl"))))
For Loop in R not printing what I need
if you are using for loop we need to mention jth interation equals to i.
for(i in list1){
for(j in list2[list1==i]){
print(i + j)
}
}
[1] 3
[1] 6
[1] 9
[1] 12
Role of print() function in a for loop
The reason for this is, that all the stuff inside the loop gets evaluated, but never returned to somewhere. Though print deliver something I wouldn't advise it, because you can't use these values later, because they get returned to the console rather then the global environment. Instead you might want to assign them to something.
For example:
#example data
df <- data.frame(x = 1:10, y = rnorm(10))
#it is good to create the output in the desired length first
#it is much more efficient in terms of speed an memory beeing used but here it don't really matter
ret <- vector("list", NCOL(df))
for(x in seq_len(NCOL(df))){
ret[[x]] <- c(mean(df[[x]]),
var(df[[x]]),
sd(df[[x]]))
}
ret
Though I don't advise that neither. For the most (if not all things) you can do with a for loop you can use the apply family of functions from base r or the map function from purrr. This would look that way:
library(purrr)
map(df, ~c(mean(.), var(.), sd(.)))
#or even save it with names
ret <- map(df, ~c(mean = mean(.), var = var(.), sd = sd(.)))
ret
The apply/map variants are faster & shorter, but more importantly for me easier to understand and have less room for errors. Though there are a hole bunch of other arguments why you might want to use apply/map.
Loop does not print function output
I'm using the example data from the function help for boot.ci
since you haven't included any. Some functions need to be forced to print when they're inside other functions, often using the function print
. Copy the format of this:
library(boot)
ratio <- function(d, w) sum(d$x * w)/sum(d$u * w)
city.boot <- boot(city, ratio, R = 999, stype = "w", sim = "ordinary")
for (i in letters[1:5]) {
cat("This is number:\n", i, "\n")
print(boot.ci(city.boot, conf = c(0.90, 0.95),type = c("bca")))
}
Notice that you don't need to paste
inside of cat
. But in general it is good to avoid cat
as print
is a slightly gentler function. Using cat
can lead to annoying messages that are hard later.
In future, please supply reproducible examples! (And let us know which packages you're using!)
Related Topics
Long/Bigint/Decimal Equivalent Datatype in R
Calculating Cumulative Sum For Each Row
Create a Group Number For Each Consecutive Sequence
How to Extract Plot Axes' Ranges For a Ggplot2 Object
Dummy Variables from a String Variable
Subscript Out of Bounds - General Definition and Solution
Ggplot2: Histogram With Normal Curve
R: Use Magrittr Pipe Operator in Self Written Package
Sample from Vector of Varying Length (Including 1)
How Does One Reorder Columns in a Data Frame
Clang-7: Error: Linker Command Failed With Exit Code 1 For Macos Big Sur
R Spreading Multiple Columns With Tidyr
Ggplot2 Two-Line Label With Expression
Replace Na in Column With Value in Adjacent Column