遍历数据框中的年度命名数据

时间:2018-07-31 07:17:33

标签: r dataframe

这似乎是一个非常愚蠢的问题,但是是否有一种简单的方法可以在数据框名称中循环多年? 我的程序非常简单,每年只需要添加3列即可。

df$ges_2005 <- df$bKU3_2005 + df$bKUe3_2005 + df$bKSch_2005
df$ges_2006 <- df$bKU3_2006 + df$bKUe3_2006 + df$bKSch_2006
df$ges_2007 <- df$bKU3_2007 + df$bKUe3_2007 + df$bKSch_2007
df$ges_2008 <- df$bKU3_2008 + df$bKUe3_2008 + df$bKSch_2008
df$ges_2009 <- df$bKU3_2009 + df$bKUe3_2009 + df$bKSch_2009
df$ges_2010 <- df$bKU3_2010 + df$bKUe3_2010 + df$bKSch_2010

后面的变量都存在于2000-2018年的数据帧中,我想知道是否还能以某种方式从复制和粘贴此代码20次中获得方法?

1 个答案:

答案 0 :(得分:0)

一个可能的解决方案如下所示:

using System;
using System.Linq.Expressions;
using System.Reflection;

namespace ConsoleAppTest2
{
    class Program
    {
        static void Main(string[] args)
        {
            var myModel = new MyModel();

            var cmb = ConsoleModelBuilder<MyModel>.RequestFromComsole(myModel)
                .FillProp(x=>x.MethodName)
                .FillProp(x => x.Birthday);
            Console.ReadLine();
        }
    }

    internal class MyModel
    {
        public int MethodName { get; set; }
        public DateTime Birthday { get; set; }

    }

    internal class ConsoleModelBuilder<T>
    {
        public T Model { get; private set; }

        public static ConsoleModelBuilder<T> RequestFromComsole(T obj)
        {
            return new ConsoleModelBuilder<T>() { Model = obj };


        }

        public ConsoleModelBuilder<T> FillProp<TProperty>(Expression<Func<T, TProperty>> propertyLambda)
        {
            PropertyInfo info = GetPropertyInfo(Model, propertyLambda);

            Console.WriteLine($"Hi, Please enter {info.Name} value as {info.PropertyType.Name}:");
            //Code to parse console input and fill property of Model
            return this;
        }


        public PropertyInfo GetPropertyInfo<TSource, TProperty>(
    TSource source,
    Expression<Func<TSource, TProperty>> propertyLambda)
        {
            Type type = typeof(TSource);

            MemberExpression member = propertyLambda.Body as MemberExpression;
            if (member == null)
                throw new ArgumentException(string.Format(
                    "Expression '{0}' refers to a method, not a property.",
                    propertyLambda.ToString()));

            PropertyInfo propInfo = member.Member as PropertyInfo;
            if (propInfo == null)
                throw new ArgumentException(string.Format(
                    "Expression '{0}' refers to a field, not a property.",
                    propertyLambda.ToString()));

            if (type != propInfo.ReflectedType &&
                !type.IsSubclassOf(propInfo.ReflectedType))
                throw new ArgumentException(string.Format(
                    "Expression '{0}' refers to a property that is not from type {1}.",
                    propertyLambda.ToString(),
                    type));

            return propInfo;
        }
    }
}