Problem with for loop: arguments imply differing number of rows: 0, 1

Now, in a separate file (not part of your function), could you run this code?

for (x in vectorstates){
  filtered <- filter(removal, removal$State %in% x)
  datafiltered <- filtered[order(filtered[,y],filtered[,'Hospital.Name']),]
  hospital <- filter(datafiltered, datafiltered[,y] %in% datafiltered[z,y])
  printdata <- data.frame(name = hospital$Hospital.Name)
  ID <- data.frame(x)
  Collected <- cbind(printdata,ID)
  print(Collected)
}
for (x in vectorstates){
filtered <- filter(removal, removal$State %in% x)
datafiltered <- filtered[order(filtered[,y],filtered[,'Hospital.Name']),]
hospital <- filter(datafiltered, datafiltered[,y] %in% datafiltered[z,y])
printdata <- data.frame(name = hospital$Hospital.Name)
ID <- data.frame(x)
Collected <- cbind(printdata,ID)
print(Collected)
}

gives me this output

    name  x
1 JACKSON MEDICAL CENTER AL
                                              name  x
1 PEACEHEALTH KETCHIKAN MEDICAL             CENTER AK
                               name  x
1 BANNER THUNDERBIRD MEDICAL CENTER AZ
2               ORO VALLEY HOSPITAL AZ
                     name  x
1 ARKANSAS HEART HOSPITAL AR
                          name  x
1 SAINT VINCENT MEDICAL CENTER CA
                                      name  x
1 CENTURA HEALTH-PORTER ADVENTIST HOSPITAL CO
                     name  x
1 YALE-NEW HAVEN HOSPITAL CT
                   name  x
1 ST FRANCIS HEALTHCARE DE
                 name  x
1 PROVIDENCE HOSPITAL DC
                   name  x
1 DELRAY MEDICAL CENTER FL
                            name  x
1 BARROW REGIONAL MEDICAL CENTER GA
                 name  x
1 HILO MEDICAL CENTER HI
                       name  x
1 BINGHAM MEMORIAL HOSPITAL ID
                                   name  x
1 ADVENTIST LA GRANGE MEMORIAL HOSPITAL IL
2            ELMHURST MEMORIAL HOSPITAL IL
                                 name  x
1 WILLIAM N WISHARD MEMORIAL HOSPITAL IN
            name  x
1 MERCY HOSPITAL IA
                                 name  x
1 COFFEYVILLE REGIONAL MEDICAL CENTER KS
2        HERINGTON MUNICIPAL HOSPITAL KS
                   name  x
1 WAYNE COUNTY HOSPITAL KY
                        name  x
1 OAKDALE COMMUNITY HOSPITAL LA
                                 name  x
1           HOULTON REGIONAL HOSPITAL ME
2 REDINGTON FAIRVIEW GENERAL HOSPITAL ME
                     name  x
1 MEDSTAR HARBOR HOSPITAL MD
                                  name  x
1 BETH ISRAEL DEACONESS MEDICAL CENTER MA
                         name  x
1 HURON VALLEY-SINAI HOSPITAL MI
                                    name  x
1 MAYO CLINIC HEALTH SYSTEM - NEW PRAGUE MN
                                        name  x
1 KING'S DAUGHTERS MEDICAL CENTER-BROOKHAVEN MS
                             name  x
1 MISSOURI BAPTIST MEDICAL CENTER MO
                 name  x
1 ST JAMES HEALTHCARE MT
                               name  x
1 JEFFERSON COMMUNITY HEALTH CENTER NE
2          TRI VALLEY HEALTH SYSTEM NE
                   name  x
1 MOUNTAINVIEW HOSPITAL NV
                       name  x
1 FRISBIE MEMORIAL HOSPITAL NH
                    name  x
1 KIMBALL MEDICAL CENTER NJ
                                    name  x
1         CROWNPOINT HEALTHCARE FACILITY NM
2 REHOBOTH MCKINLEY CHRISTIAN HEALTH SER NM
                            name  x
1 NEW YORK-PRESBYTERIAN HOSPITAL NY
                                name  x
1 PRESBYTERIAN HOSPITAL HUNTERSVILLE NC
                                    name  x
1 WEST RIVER REGIONAL MEDICAL CENTER-CAH ND
                      name  x
1 GRAND LAKE HEALTH SYSTEM OH
                                name  x
1 INTEGRIS CLINTON REGIONAL HOSPITAL OK
                               name  x
1 PROVIDENCE NEWBERG MEDICAL CENTER OR
                 name  x
1 BLOOMSBURG HOSPITAL PA
                name  x
1 HOSPITAL DAMAS INC PR
                   name  x
1 RHODE ISLAND HOSPITAL RI
                          name  x
1 GEORGETOWN MEMORIAL HOSPITAL SC
2     LORIS COMMUNITY HOSPITAL SC
                                            name  x
1 AVERA HAND COUNTY MEMORIAL HOSPITAL AND CLINIC SD
2                           AVERA QUEEN OF PEACE SD
                               name  x
1 FRANKLIN WOODS COMMUNITY HOSPITAL TN
                             name  x
1   METHODIST SUGAR LAND HOSPITAL TX
2 TOMBALL REGIONAL MEDICAL CENTER TX
                                 name  x
1 CENTRAL VALLEY MEDICAL CENTER - CAH UT
                  name  x
1 MT ASCUTNEY HOSPITAL VT
Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 0, 1

And did you get any errors?

yes the error above, and also the format in the above printout is incorrect; it should print a dataframe containing a list of the states and a corresponding hospital for each state in that list....

name  x
1 JACKSON MEDICAL CENTER AL
                                              name  x
1 PEACEHEALTH KETCHIKAN MEDICAL             CENTER AK
                               name  x
1 BANNER THUNDERBIRD MEDICAL CENTER AZ
2               ORO VALLEY HOSPITAL AZ
                     name  x
1 ARKANSAS HEART HOSPITAL AR
                          name  x
1 SAINT VINCENT MEDICAL CENTER CA
                                      name  x
1 CENTURA HEALTH-PORTER ADVENTIST HOSPITAL CO
                     name  x
1 YALE-NEW HAVEN HOSPITAL CT
                   name  x
1 ST FRANCIS HEALTHCARE DE
                 name  x
1 PROVIDENCE HOSPITAL DC
                   name  x
1 DELRAY MEDICAL CENTER FL
                            name  x
1 BARROW REGIONAL MEDICAL CENTER GA
                 name  x
1 HILO MEDICAL CENTER HI
                       name  x
1 BINGHAM MEMORIAL HOSPITAL ID
                                   name  x
1 ADVENTIST LA GRANGE MEMORIAL HOSPITAL IL
2            ELMHURST MEMORIAL HOSPITAL IL
                                 name  x
1 WILLIAM N WISHARD MEMORIAL HOSPITAL IN
            name  x
1 MERCY HOSPITAL IA
                                 name  x
1 COFFEYVILLE REGIONAL MEDICAL CENTER KS
2        HERINGTON MUNICIPAL HOSPITAL KS
                   name  x
1 WAYNE COUNTY HOSPITAL KY
                        name  x
1 OAKDALE COMMUNITY HOSPITAL LA
                                 name  x
1           HOULTON REGIONAL HOSPITAL ME
2 REDINGTON FAIRVIEW GENERAL HOSPITAL ME
                     name  x
1 MEDSTAR HARBOR HOSPITAL MD
                                  name  x
1 BETH ISRAEL DEACONESS MEDICAL CENTER MA
                         name  x
1 HURON VALLEY-SINAI HOSPITAL MI
                                    name  x
1 MAYO CLINIC HEALTH SYSTEM - NEW PRAGUE MN
                                        name  x
1 KING'S DAUGHTERS MEDICAL CENTER-BROOKHAVEN MS
                             name  x
1 MISSOURI BAPTIST MEDICAL CENTER MO
                 name  x
1 ST JAMES HEALTHCARE MT
                               name  x
1 JEFFERSON COMMUNITY HEALTH CENTER NE
2          TRI VALLEY HEALTH SYSTEM NE
                   name  x
1 MOUNTAINVIEW HOSPITAL NV
                       name  x
1 FRISBIE MEMORIAL HOSPITAL NH
                    name  x
1 KIMBALL MEDICAL CENTER NJ
                                    name  x
1         CROWNPOINT HEALTHCARE FACILITY NM
2 REHOBOTH MCKINLEY CHRISTIAN HEALTH SER NM
                            name  x
1 NEW YORK-PRESBYTERIAN HOSPITAL NY
                                name  x
1 PRESBYTERIAN HOSPITAL HUNTERSVILLE NC
                                    name  x
1 WEST RIVER REGIONAL MEDICAL CENTER-CAH ND
                      name  x
1 GRAND LAKE HEALTH SYSTEM OH
                                name  x
1 INTEGRIS CLINTON REGIONAL HOSPITAL OK
                               name  x
1 PROVIDENCE NEWBERG MEDICAL CENTER OR
                 name  x
1 BLOOMSBURG HOSPITAL PA
                name  x
1 HOSPITAL DAMAS INC PR
                   name  x
1 RHODE ISLAND HOSPITAL RI
                          name  x
1 GEORGETOWN MEMORIAL HOSPITAL SC
2     LORIS COMMUNITY HOSPITAL SC
                                            name  x
1 AVERA HAND COUNTY MEMORIAL HOSPITAL AND CLINIC SD
2                           AVERA QUEEN OF PEACE SD
                               name  x
1 FRANKLIN WOODS COMMUNITY HOSPITAL TN
                             name  x
1   METHODIST SUGAR LAND HOSPITAL TX
2 TOMBALL REGIONAL MEDICAL CENTER TX
                                 name  x
1 CENTRAL VALLEY MEDICAL CENTER - CAH UT
                  name  x
1 MT ASCUTNEY HOSPITAL VT
Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 0, 1

we can see above that some states have two hospitals assigned, but each should only have one...

So which state produces the error? Check that one with the previous line-by-line approach you used with CA.

yes for example, when I replace x with 'NE', I get this output:

Rankall('Pneumonia','best')
hospital.Hospital.Name X.NE.
1 BOX BUTTE GENERAL HOSPITAL NE
Rankall('Pneumonia','worst')
NULL
Rankall('Pneumonia','worst')
NULL
Rankall('Pneumonia',2)
NULL
Rankall('Pneumonia',1)
NULL
Rankall('Pneumonia',19)
NULL

so only the 'best' option for z works for the state NE

If you keep running the function, it makes it difficult to track down where the error is coming from, and 'NE' did not produce an error in this output you posted:

Find which state caused the error and run this code with that state as x, inspecting every object created as you run each step:

  filtered <- filter(removal, removal$State %in% x)
  datafiltered <- filtered[order(filtered[,y],filtered[,'Hospital.Name']),]
  hospital <- filter(datafiltered, datafiltered[,y] %in% datafiltered[z,y])
  printdata <- data.frame(name = hospital$Hospital.Name)
  ID <- data.frame(x)
  Collected <- cbind(printdata,ID)
  print(Collected)

@dromano I think I have figured out where my error is: using the state MA as an example:

filtered <- filter(removal, removal$State %in% 'MA')
filtered <- filtered[!is.na(filtered['Pneumonia']),]
datafiltered <- filtered[order(filtered[,'Pneumonia'],filtered[,'Hospital.Name']),]
View(datafiltered)
hospital <- filter(datafiltered, datafiltered[,'Pneumonia'] %in% datafiltered[1,'Pneumonia'])

here I am trying to filter out the name of the hospital that corresponds to the lowest value in the column Pneumonia, i.e. the 1st row:

but the function is printing the first 2 rows, not the 1st row (suprisingly)...

I feel that this is because both of the first 2 values in the Pneumonia column are the same...

However, I have ordered the dataframe by the column 'Pneumonia' and then by the column 'State' to avoid this problem with TIES:

Do you have any idea on how I should proceed; I have identified the states 'MA' and 'UT' as the issue...

That depends on what your goal is, which isn't clear to me -- what are you trying to achieve but haven't?

The code above should only print the first row of the dataframe, not the first 2 rows... which is why I'm confused.

hospital <- filter(datafiltered, datafiltered[,'Pneumonia'] %in% datafiltered[1,'Pneumonia'])

The 1 indicates printing the first row.

What is the value of datafiltered[1,'Pneumonia'] when the state is 'MA'?

datafiltered[1,'Pneumonia']
[1] 8.2

In this case it correctly prints only 1 value!!

but because there are 2 x 8.2, (1st and 2nd row), the system is confused..

And what is the value of datafiltered[,'Pneumonia'] %in% datafiltered[1,'Pneumonia']?

datafiltered[,'Pneumonia'] %in% datafiltered[1,'Pneumonia']
[1] TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[24] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[47] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

@dromano

This is the vector you're asking R to use to pick out the rows you want -- all the ones that match 8.2, which is the first two, as shown by the TRUE and FALSE values you see.

If you just want the first row, you need to use slice(), not filter(), specifically

hospital <- slice(datafiltered, 1)

instead of

hospital <- filter(datafiltered, datafiltered[,'Pneumonia'] %in% datafiltered[1,'Pneumonia'])

yes thank you so much!

This works too:

hospital <- datafiltered[1,]

1 Like
library(tidyverse)
set.seed(42) 
vector_states <- LETTERS[1:3]


states_vec <- sample(vector_states,size=10,replace=TRUE) %>% sort()
hospital_letter1 <- sample(letters[1:26],size=10,replace=FALSE)
hospital_letter2 <- sample(letters[1:26],size=10,replace=FALSE)
hospital <- paste0(hospital_letter1,hospital_letter2)
pneumonia <- rnorm(10)
df <- tibble( state=states_vec,
              hospital =hospital,
              pneumonia=pneumonia)

#no function needed to find the minimum hospital pneumonia per state
min_vals_df <- group_by(df,
                        state) %>% summarise(min_pneumonia = min(pneumonia))

min_vals_df_with_hosps <- left_join(x = min_vals_df,
                                    y = df, 
                                    by = c("state"="state","min_pneumonia"="pneumonia")) 
> min_vals_df_with_hosps
# A tibble: 3 x 3
state min_pneumonia hospital
<chr>         <dbl> <chr>   
1 A            -0.162 de      
2 B            -0.394 rh      
3 C            -0.949 ij  


#with a function
get_min_pnu_and_hosp <- function(x){
  min_vals_df <- filter(df,state==x) %>% group_by(
                          state) %>% summarise(min_pneumonia = min(pneumonia))
  
  min_vals_df_with_hosps <- left_join(x = min_vals_df,
                                      y = df, 
                                      by = c("state"="state","min_pneumonia"="pneumonia")) 
}

result <- get_min_pnu_and_hosp("A")
result


library(purrr)
#map over the function return a list of 1 row tibbles
results <- map(
  vector_states,
  ~get_min_pnu_and_hosp(.)
)

results2 <- map_dfr(
  vector_states,
  ~get_min_pnu_and_hosp(.)
)

yes, I know that's the solution (this is part of a course I'm doing online) but I wanted to hide myself from the answers and try it my own way!

thanks so much anway @nirgrahamuk

The only problem I'm having now is that when there is no hospital name, as not all the hospitals are present in all states, it is printing "character(0)", which is stopping me from creating the dataframe. If I converted character(0) to NA would that allow me to create the dataframe?

The only problem I'm having now is that when there is no hospital name, as not all the hospitals are present in all states, it is printing "character(0)", which is stopping me from creating the dataframe. If I converted character(0) to NA would that allow me to create the dataframe?